简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM