2013-03-20 33 views
5

我想在另一个结果集中使用find查询的结果集。我无法用英语很好地解释这种情况。我会尝试使用一些代码。NodeJS - 如何发送一个变量嵌套回调? (MongoDB查找查询)

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

首先,我得到所有的人找到谁被命名为约翰。然后我把这些人当作allJohns。其次,我得到每个Johns中的所有宠物,不同的找到查询。

在第二个回调,我得到一个重新每一个宠物。但是当我想要展示哪些约翰是他们的主人时,我总是得到同样的约翰。

所以,问题是:我怎么能单独发送的每约翰第二嵌套回调,他们将一起作为真正的主人和宠物。

我需要每一个约翰复制,但我不知道我怎么能做到这一点。

+0

有没有在上面一个错字?你的意思是忘记写回调函数作为Animals.find()的第二个参数吗? – ravi 2013-03-21 13:56:51

回答

5

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

你必须给更多的浓度对异步特性。

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