NodeJS - how to send a variable to nested callbacks? (MongoDB find queries)
callback, function, javascript, mongodb, node.js
Solution
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 );
});
});
});
});
Problem
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.