【发布时间】:2015-05-05 08:10:07
【问题描述】:
我正在尝试找到一种方法,让自己的代码尽可能干净,以使用多个复杂的查询。
我在 MongoDB 中有 2 个文档。 第一个是关注者,第二个是事件。
第一个查询:获取特定用户的所有关注者。 第二个查询:获取所有关注者的所有事件并按日期排序。
我不知道如何进行第二个查询。
可能是这样的:
Event.find({ "$or" : [
{
'userId': followers[0].id,
},
{
'userId': followers[1].id,
},
{
'userId': followers[2].id,
},
]});
但这对我来说并不是一个非常干净的代码。
【问题讨论】:
-
我认为您需要的是
$in运算符;var userIds = [followers[0].id, followers[1].id, followers[2].id]; Event.find({ 'userId': { $in: userIds } }, function(err, result){ ... }); -
@chridam 对我来说似乎是一个“答案”。特别是如果您能解释
$or与$in的关系。我只是想:{ "userId": { "$in": followers.map(function(follower) { return follower.id })) } } -
@NeilLunn 感谢您的建议,在这种情况下我认为
map函数更可取。
标签: javascript node.js mongodb mongoose mongodb-query