Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through mongoose find result

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.

like image 913
Pio Avatar asked Apr 06 '13 16:04

Pio


2 Answers

You forgot to initialize i:

for (var i = 0;i<data.length;i++){
//        ^^^^
  console.log(data[i].name);
}
like image 56
robertklep Avatar answered Oct 21 '22 15:10

robertklep


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
});
like image 41
Ali Avatar answered Oct 21 '22 14:10

Ali