Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - how to send a variable to nested callbacks? (MongoDB find queries)

I want to use result set of a find query in another result set. I couldn't explain this situation in english very well. I will try to use some code.

People.find( { name: 'John'}, function( error, allJohns ){
    for( var i in allJohns ){
        var currentJohn = allJohns[i];
        Animals.find( { name: allJohns[i].petName }, allJohnsPets ){
            var t = 1;
            for( var j in allJohnsPets ){
                console.log( "PET NUMBER ", t, " = " currentJohn.name, currentJohn.surname, allJohnsPets[j].name );
                t++;
            }
        }
    }
});

Firstly, I get all people with find who are named John. Then I take those people as allJohns.

Secondly, I get all pets of every Johns one by one in different find queries.

In second callback, I get every pet one by one again. But when I want to display which John is their owners, I always got same John.

So, the question is: how can I send every John separately to the second nested callback and they will be together as real owners and pets.

I need to copy every John but I have no idea how can I do this.

like image 290
Rephisto Avatar asked Mar 20 '13 15:03

Rephisto


2 Answers

Javascript has no block scope, only function scope. Instead of for .. in .., using forEach will create a new scope for each loop:

People.find( { name: 'John'}, function( error, allJohns ){
  allJohns.forEach(function(currentJohn) { 
    Animals.find( { name: currentJohn.petName }, function(err, allJohnsPets) { 
      allJohnsPets.forEach(function(pet, t) { 
        console.log( "PET NUMBER ", t + 1, " = ", currentJohn.name, currentJohn.surname, pet.name );
      });
    });
  });
});
like image 74
robertklep Avatar answered Oct 07 '22 02:10

robertklep


You have to give more concentration on asynchronous nature.

People.find( { name: 'John'}, function( error, allJohns ){
    for( var i=0; i<allJohns.length; i++ ){
     (function(currJohn){
         var currentJohn = currJohn;
         Animals.find( { name: currentJohn.petName }, function(error, allJohnsPets){

             for(var j=0; j<allJohnsPets.length; j++){
       console.log( "PET NUMBER ", (j+1), " = " currentJohn.name, currentJohn.surname, allJohnsPets[j].name );
             }
          })

      })(allJohns[i]);
    }
});
like image 24
HILARUDEEN S ALLAUDEEN Avatar answered Oct 07 '22 01:10

HILARUDEEN S ALLAUDEEN