2016-03-27 3 views
0

Я имею коллекцию пользователей типа -Как вложить запросы mongodb через node.js?

{ 
"_id" : ObjectId("56f60e4eea8af4670408483e"), 
"twitterHandle" : "shrutip", 
"firstName" : "Shruti", 
"lastName" : "Patil", 
"emailID" : "[email protected]", 
"password" : "91382451347786e9b8f2f3817b27a2adfec1880c", 
"phoneNumber" : "98739458789", 
"location" : "San Jose", 
"birthYear" : 1992, 
"birthMonth" : 1, 
"birthDay" : 10, 
"followers" : [ 
    "abhayp", 
    "anupd", 
    "lubdhal", 
    "poojag", 
    "prashantb", 
    "pratiksanglikar", 
    "shaileshyedge", 
    "shrutip" 
], 
"following" : [ 
    "abhinavk", 
    "anupd", 
    "hiteshn", 
    "lubdhal", 
    "omkarn", 
    "poojag", 
    "pratiksanglikar", 
    "shaileshyedge", 
    "shrutip" 
], 
"tweets" : [ 
    { 
     "tweet_id" : "3c50e98cf0c2298f40f98a013cd4a18a1443b7ac", 
     "tweet_text" : "At BJP youth wing meet, seniors worry over #JNU controversy, and not #RamTemple.", 
     "createdOn" : ISODate("2016-03-07T23:37:27Z"), 
     "tags" : [ 
      "JNU", 
      "RamTemple" 
      ] 
     } 
    ] 
} 

Я хочу, чтобы создать канал (все твиты пользователей данного пользователя следующие в порядке возрастания даты) для данного пользователя. Я получил список пользователей, которым данный пользователь следит, но мне нужно найти твиты найденных пользователей. Как это сделать в node.js? Как вложить эти запросы?
Что я сделал до сих пор находится в списке ниже -

var cursor = MongoDB.collection("users").find({ 
    "twitterHandle": twitterHandle 
}); 
cursor.each(function(err, doc) { 
    assert.equal(err, null); 
    if (doc != null) { 
     var followingCursor = MongoDB.collection("users").find({ twitterHandle: { $in: doc.following } }); 
     followingCursor.each(function (err, following) { 
      if(following != null) { 
       feed.push(following.tweets); 
      } 
     }); 
     promise.resolve(feed); 
    } 
}); 

Но так или иначе, обещание получает решить до второй запрос выполняется. Как обеспечить выполнение всех итераций followingCursor.each до того, как я верну обещание?

ответ

0

В конце концов я сам выяснил ответ.

if (doc != null) { 
    var followingCursor = MongoDB.collection("users").find({ twitterHandle: { $in: doc.following } }); 
    followingCursor.each(function (err, following) { 
     if(following != null) { 
      feed.push(following.tweets); 
     } 
    }); 
    promise.resolve(feed); 
} 

В приведенном выше коде, обещание должны быть решены, если условие following != null терпит неудачу. Видимо, драйвер MongoDB возвращает null, когда значения в конце курсора. Правильный код выглядит следующим образом:

if (doc != null) { 
     var followingCursor = MongoDB.collection("users").find({ twitterHandle: { $in: doc.following } }); 
     followingCursor.each(function (err, following) { 
      if(following != null) { 
       feed = feed.concat(following.tweets); 
      } else { 
       promise.resolve(feed); 
      } 
     }); 
    } 
Смежные вопросы