使用 $or 在 mongoose 中复杂的多个查询

Complex multiple queries in mongoose with $or

我正在努力寻找一种方法,让自己尽可能干净地使用多个复杂查询的代码。

我在 MongoDB 中有 2 个文档。 第一个是关注者,第二个是事件。

第一个查询:获取特定用户的所有关注者。 第二个查询:获取所有关注者的所有事件并按日期排序。

我不知道如何进行第二个查询。

也许是这样的:

Event.find({ "$or" : [
                        {
                            'userId': followers[0].id,
                        },
                        {
                            'userId': followers[1].id,
                        },
                        {
                            'userId': followers[2].id,
                        },
                        ]});

但我觉得这不是一个非常干净的代码。

我认为您需要的是 $in operator. The $in operator only takes one index whilst the $or operator takes more (one per clause). The documentation 还明确指出:

When using $or with that are equality checks for the value of the same field, use the $in operator instead of the $or operator.

您可以按如下方式修改您的查询:

var userIds = [followers[0].id, followers[1].id, followers[2].id]; 
Event.find({ 'userId': { $in: userIds } }, function(err, result){ ... });

或者如 Neil Lunn 所建议的那样,另一种解决方法是使用本机映射方法生成所需用户 ID 的数组:

Event.find({
     "userId": {
          "$in": followers.map(function (follower){
               return follower.id
           }))
     }
}, function(err, result){ ... });