如何通过node.js嵌套mongodb查询?

时间:2016-03-27 07:11:32

标签: javascript node.js mongodb

我有一个类型的用户集合 -

{
"_id" : ObjectId("56f60e4eea8af4670408483e"),
"twitterHandle" : "shrutip",
"firstName" : "Shruti",
"lastName" : "Patil",
"emailID" : "shrutip@gmail.com",
"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);
    }
});

但不知何故,承诺在第二个查询执行之前得到解决。 在返回promise之前,如何确保followingCursor.each的所有迭代都已执行?

1 个答案:

答案 0 :(得分: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条件失败,则应解析promise。 显然,当游标结束时,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);
            }
        });
    }