Reputation: 4064
I have some trouble getting out data from the result of a query in mongoose: here is my function:
getNinjas : function(res){
var twisted = function(res){
return function(err, data){
if (err){
console.log('error occured');
return;
}
res.send('My ninjas are:\n');
for (var i;i<data.length;i++){
console.log(data[i].name);
}
//I need to process my data one by one here
}
}
Ninja.find({},'name skill',twisted(res));
}
So if I console.log(data)
in the getNinjas function, I get the result of my query. How can I access each record one by one? I get nothing in the console like this.
Upvotes: 9
Views: 15753
Reputation: 2396
Since you ask how to access each record one by one, it's good to have forEach
in your arsenal other than the standard for
loop. Once you've crossed the error checking if
:
data.forEach(function(record){
console.log(record.name);
// Do whatever processing you want
});
Upvotes: 4
Reputation: 203304
You forgot to initialize i
:
for (var i = 0;i<data.length;i++){
// ^^^^
console.log(data[i].name);
}
Upvotes: 7