array push of records obtained from mongo db - arrays

In MEAN stack, I am trying to store the records obtained from mongo db in an array, but I am not able to store the record in an array.
This is my code, I am trying to push the records obtained from projectimage to fulldetails[] array, but it failed. Suggest me the possible solution to store the mongo db records to array
var express = require("express"),
router = express.Router(),
project = require("../../models/project.js"),
projectimage = require("../../models/projectimages.js"),
var details=data;
var fulldetails=[];
for (var i = 0; i < details.length; i++) {
var prjct_id=details[i]._id;
console.log('below'+i);
fulldetails.push(details[i]);
projectimage.findOne({projectId: prjct_id}, function(err, data){
fulldetails.concat(data);
});
console.log(fulldetails);
return false;
}

I think what do you want is to get an array from your Mongo collection, correct me if I am wrong.
I am also assuming that Mongo query runs successfully, and returns the records correctly. then you can use toArray function to get array in callback.
// let's say Furniture is your collection
let furniture = Furniture.find({});
let details = [];
furniture.toArray((err, array) => {
if (err) return;
details = array; // now details has your collections' documents
});
For more refer this
Let me know if this is not what you were looking for.

I think you're trying to get a flat array of full details. If my assumption is correct, you could try my solution here:
var fulldetails=[];
for (var i = 0; i < details.length; i++) {
var prjct_id=details[i]._id;
projectimage.find({projectId: prjct_id}).toArray(function(err, data){ //convert data to array first
console.log(data);
fulldetails.concat(data); // concat data to fulldetails to get a flat array
});
}

Related

Can AppMaker be used with SQL Server

I understand AppMaker can be used with PostgreSQL and MySQL but the documentation says you can use your own data source. This is a bit ambiguous and I am trying to find out specifically if I can use an existing SQL Server database. I've spoken with Google's support team but they were unable to answer and directed me to ask a question here. Thanks in advance :-)
Quick answer is yes but Cloud SQL is easier and works better.
Long answer:
App Maker does support SQL using REST and JDBC however it is much harder than using their own CloudSQL model. some code for JDBC from when i last used it:
function get_data() {
var queryStr = 'SELECT * FROM users'; //SQL query
var calcRecords = []; //empty array to put records into
var connection = Jdbc.getConnection(dbUrl, user, userPwd); //connect to database
var statement = connection.prepareStatement(queryStr); //prepared statement
var results = statement.executeQuery(); //execute prepared query
try {
while (results.next()) {
var calcRecord = app.models.test.newRecord();
calcRecord.id = results.getInt(1); //data source test row id
calcRecord.user = results.getString(2); //data source test row user
calcRecord.passwd = results.getString(3); //data source test row passwd
calcRecords.push(calcRecord); //append to 2D array
}
results.close(); //close the results
statement.close(); //close the connection
} catch (err) {
console.error('SQL query failed: ' + err);
}
return calcRecords;
}
The equivalent Google Cloud SQL:
function get_users(){
var ds=app.datasource.Users.Items;
var data = [];
for(var i = 0; i < Items.length; i++){
tmp = [];
tmp.push(Items[i].id); //the id
tmp.push(Items[i].user); //the username
tmp.push(Items[i].password); //the password
data.push(tmp); //push to create 2D array
}
return data;
}
Doing query is a little harder and requires server code (so async callbacks), but populating Widgets like dropdown and implementing tables is a lot easier, usually requiring a couple of clicks rather than a lot of code.

Mongoose Model, cleaning/parsing an Array efficiently

I am having some issues with a mongoose array, it's likely due to my lacking understanding of the library, and I can't find the exact answer I'm looking for in the docs.
For starters I have my schema and model declarations:
const gConfig = new Schema({ aList: Array, maxChanLimit: Number }), globalConfiguration = mongoose.model('globalConfig', gConfig);
And I have my command which fetches the array, parses out _id, then pushes the new item to the array, and overwrites the existing one in the database.
if((message.author.id === g.ownerID) && (g.id.toString() === tocGuild) && message.content.startsWith("!updatealist"))
{
let mc = message.content.replace("!updatealist ", "");
globalConfiguration.findOneAndUpdate({},{$push: {"aList":mc }}, { upsert: true }, function(err, data) {
if (err) return console.log(err);
var str = JSON.stringify(data); str = str.replace(RegExp(/"_id"|"__v"|'/g),""); var arr = str.split(`","`);
});
}
I feel like there has to be a better way to do this, I've tried something like this based on what I've read:
globalConfiguration.findOneAndUpdate({},{$push: {"-_id aList":mc }}
However this did not remove _id from the array. I suppose how I'm doing it is a way to do it, but I know it isn't efficient, and isn't dynamic at all, it's also extremely bulky in terms of code and could be streamlined using the library.
In practice, what is the best way to properly read an array from a model with Mongoose? How do you read from the array without the additional objects Mongoose adds by default? What is the best way to add an item to an existing model?
Any help is appreciated, thank you.
if you want to have more control over the updating process, you can do it like this, in the mongoose documents it suggest you can first query the item/document you want to update, once that document is queried and there, you can make changes to it such as if it contains an array , you can push to it or pop from it or what ever..
its in your control
so,
if((message.author.id === g.ownerID) && (g.id.toString() === tocGuild) && message.content.startsWith("!updatealist"))
{
let mc = message.content.replace("!updatealist ", "");
globalConfiguration.findOne({"your query"}, function(err, data) {
if (err) throw (err);
data.array.push("something");
data.save();// save it again with updates
var str = JSON.stringify(data); str = str.replace(RegExp(/"_id"|"__v"|'/g),""); var arr = str.split(`","`);
});
}

Find the element in custom array and append the value in one of its property(which is also an array) of custom array in swift

#objc class CplModel:NSObject {
var cplModel:UserCplModel = UserCplModel(json: [:])
var courseData:[CourseModel] = [CourseModel]()
var feedData:[FeedsModel] = [FeedsModel]()
var assessmentData:[AssessmentModel] = [AssessmentModel]()
var userCourseData:[UserCourseModel] = [UserCourseModel]()
init(jsonUserCPlModel:[String:Any]){
if let value = jsonUserCPlModel[""] as? [String:Any]{
self.cplModel = UserCplModel(json: value)
}
}
init(jsonAssessmentAndCourseData:[String]) {
}
}
I am making three Firebase calls and all three are interlinked and want to populate data in above model.
Here comes the issue:
For 1st API call I need to populate only cplModel:UserCplModel property
For 2nd ApI call I need to populate courseData:[CourseModel] and assessmentData:[AssessmentModel]
But the index should remain the same for every populating data.
I mean to say is for 1st index of cplModel, I need to insert the courseData or assessmentData but the response of 2nd API comes later and I need to insert the data in particular index only.

getting data from an object's array with vue.js

I am trying to access the following data in Vue.js
{"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
self.player = response.name works. now i need self.point
methods: {
fetchData: function() {
var self = this;
$.get("api/v1/players/1", function(response) {
console.log(response);
self.player = response.name;
self.point = response.stats.points
});
}
}
I have thus far tried response.stats["points"], response.stats[2], response.stats[ { points } ], response.stats[points]
The stats property in your json holds an array in which the first object has a property named points
So use response.stats[0].points
Keep in mind though that the stats is probably an array for a reason. It might hold more than one objects in the future, so always using the first element [0] might not be a valid approach.
I think it can help you
var json = JSON.parse(data);
json.stats[0].points
response = {"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
If you want to access the name
console.log(response.name) // Westbrook
If you want to access the stats data which contain list, simply target
let stats=response.stats[0] //By getting the first index in the list
Get the points in stats
console.log(stats.points) // 2588

Bug when sending array in node.js and socket.io

I use socket.io version 0.8.4
I have boiled down my problem to the following. I have data looking like this:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = [];
data.prop2["hey"] = "man";
I send the data from the server to the client this way:
socket.emit("data", data);
On the client side I receive the data this way:
socket.on("data", function(data){ console.log(data); });
The weird thing is:
data.prop1 = [];
data.prop1.push("man"); // This data exists in the client side data object
data.prop2 = [];
data.prop2["hey"] = "man"; // This data does not exist.
data.prop2 is just an empty array on the client side.
Is there a known bug in json serializing arrays on the form in prop2?
Thankyou in advance
EDIT:
Problem solved using this workaround:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // <= Object instead of array
data.prop2["hey"] = "man";
ECMA-262 about JSON.stringify:
The representation of arrays includes only the elements between zero and array.length – 1 inclusive. Named properties are excluded from the stringification.
Arrays are supposed to have numerical property names. So when the data.prop2 is transformed to JSON (which socket.io sends the data in, I imagine), it doesn't get the 'hey' property. If you want to use non-numerical property names, you should use objects instead of arrays:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // Notice we're creating an object, not an array.
data.prop2["hey"] = "man"; // Alternatively: data.prop2.hey = "man"
Unfortunately, Javascript doesn't really work like that.
Check out this article, about half way down. It explains the problem where you try to set data.prop2["hey"] = "man";

Resources