javascript - 使用 $or 在 mongoose 中复杂化多个查询

标签 javascript node.js mongodb mongoose mongodb-query

我正在尝试找到一种方法,让自己获得尽可能干净的代码来使用多个复杂查询。

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

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

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

也许是这样的:

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

但是对我来说这并不是一个非常干净的代码。

最佳答案

我认为您需要的是 $in运算符(operator)。 $in运算符仅采用一个索引,而 $or运算符需要更多(每个子句一个)。 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 所建议的,另一种解决方法是使用 native 映射方法来生成所需用户 ID 的数组:

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

关于javascript - 使用 $or 在 mongoose 中复杂化多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28852745/

相关文章:

node.js - 将图像从 URL 保存到 node.js 中的 S3

javascript - 如何使用平均堆栈访问 Schema.ObjectId 以获取客户端上的对象 json?

mysql - Node ssh 到 mysql - 错误 : listen EADDRINUSE 127. 0.0.1:3306

arrays - 用于嵌入式集合的 MongoDB 首选模式。文档与数组

javascript - Babylon JS 中的阴影贴图

javascript - 循环遍历表单时如何知道元素的类型?

node.js - 如何根据多个字段删除mongodb中的重复项?

mongodb - 如何通过查询字符串 Restfully 实现连接

javascript - 用 phantomJS 关闭

javascript - 在 Bootstrap 中向工具提示内部添加描述