Umesh Sehta Umesh Sehta - 1 month ago 13
Node.js Question

How to use object of one query into nested query in Mongoose

I am new in MongoDb and NodeJs, I am using Mongoose in nodejs, But I am facing a problem, I am using result object of first query into nested query but getting undefined of first query object. please give me any suggestion. Thanks.

LuckyLunch.find(criteria, function (err, lunches) { // First Query
if (err)
return;
var allLunches = lunches; // Accurate result here
for (var i = 0; i < allLunches.length; i++)
{
if (typeof allLunches[i].luckyMatch != 'undefined') {
var usernames = [];
Match.findOne(criteria2, function (err, singleMatch) { // Second Query
if (singleMatch != null) {
var userids = [];
for (var k = 0; k < singleMatch.participants.length; k++)
{
userids.push(ObjectId(singleMatch.participants[k]));
}
User.find(criteria, function (err, getusers) { // Third Query
for (var j = 0; j < getusers.length; j++)
usernames.push(getusers[j].name);

allLunches[i].luckyUsers = usernames; // allLunches[i] is undefined here.

});
}
});
}
}
});

Answer

try this,

 var getData = function(callback) {
     LuckyLunch.find(criteria, function (err, lunches) {   // First Query
      if (err) {
         callback(err); 
         return;
      }        
      var len =   lunches.length; // try to use lenches only, Accurate result here
      for (var i = 0; i < len; i++)
       {
        (function(i) { 
         if (typeof lunches[i].luckyMatch != 'undefined') {
          var usernames = [];
          Match.findOne(criteria2, function (err, singleMatch) {   // Second Query
            if (singleMatch) {
                 var userids = [];
               for (var k = 0; k < singleMatch.participants.length; k++)
               {
                  userids.push(ObjectId(singleMatch.participants[k]));
               }
                  User.find(criteria, function (err, getusers) {  // Third Query
                  for (var j = 0; j < getusers.length; j++)
                      usernames.push(getusers[j].name);

                  lunches[i].luckyUsers = usernames;  // allLunches[i] is undefined here.

               });
             }
          });
        }
        })(i);
      }

      callback(null, "put here need data to return"); //this must be end of the ur loop
  });

 }

 getData(function(err, result){

   if(err)
     console.log(err);
     else
     console.log(result); 
 });