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.
You forgot to initialize i
:
for (var i = 0;i<data.length;i++){
// ^^^^
console.log(data[i].name);
}
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With