Javascript 如何通过node.js嵌套mongodb查询?
我有一个类型的用户集合-Javascript 如何通过node.js嵌套mongodb查询?,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我有一个类型的用户集合- { "_id" : ObjectId("56f60e4eea8af4670408483e"), "twitterHandle" : "shrutip", "firstName" : "Shruti", "lastName" : "Patil", "emailID" : "shrutip@gmail.com", "password" : "91382451347786e9b8f2f3817b27a2adfec1880c", "phoneNumber" : "9873945
{
"_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"
]
}
]
}
我想为任何给定的用户创建feed(给定用户正在关注的所有推文按日期升序排列)。我得到了给定用户正在跟踪的用户列表,但我需要找到找到的用户的tweet。如何在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);
}
});
但不知何故,在第二个查询执行之前,承诺得到了解决。
如何确保在我返回承诺之前执行cursor.follower.的所有迭代?最终我自己找到了答案
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);
}
在上述代码中,如果出现以下情况,则应解决承诺问题空条件失败。
显然,当游标中的值结束时,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);
}
});
}