简体   繁体   English

NodeJS - 如何将变量发送到嵌套回调? (MongoDB查找查询)

[英]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. 所以,问题是:如何将每个John分别发送给第二个嵌套回调,他们将作为真正的所有者和宠物聚集在一起。

I need to copy every John but I have no idea how can I do this. 我需要复制每个约翰,但我不知道我怎么能这样做。

Javascript has no block scope, only function scope. Javascript没有块范围,只有函数范围。 Instead of for .. in .. , using forEach will create a new scope for each loop: 而不是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 );
      });
    });
  });
});

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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