Sails.js finds records and stores the result in var
I want to query MongoDb and store the returned records into a variable. This is what I tried in my controller:
var projects= {};
Project.find({}).exec(function findProject(err, found){
projects = found;
console.log(found.length);
while (found.length)
console.log('Found Project with name ' + found.pop().name)
});
// Returns Undefined
console.log(projects.length);
Am I doing it wrong?
How do I pass the result of .find () to variable projects?
+3
source to share
1 answer
You have to stop pop () using your array. Your object is passed by reference , not by value , so when you remove elements from one, you are actually affecting the other.
Edit:
If you are still in doubt, you can check your request:
Project.find({}).exec(function findProject(err, found){
if (err) { // here
console.log(err);
} else if (found.length == 0){
console.log("Nothing was found");
} else {
console.log(found);
}
});
Objects don't have a property .length
and that's why you get undefined
. I am guessing that you got an error and why your parameter is found
not an array.
+2
source to share