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

I want to use the search result set in another result set. I could not 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++;
            }
        }
    }
});

First, I get all the people with find that are called John. Then I take these people as allJohns .

Secondly, I get all of each John's pets, one each in different find queries .

In the second callback, I get every pet again. But when I want to show which John their owners are, I always had the same John.

, , , .

, , .

+5
2

Javascript , . for .. in .. forEach :

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 );
      });
    });
  });
});
+5

.

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]);
    }
});
+2

All Articles