【问题标题】:Mongoose - query doc if element not in arrayMongoose - 如果元素不在数组中,则查询文档
【发布时间】:2021-02-21 18:05:33
【问题描述】:

我在查询通知架构时遇到问题

receiver: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Profile' }],
readBy: [{
    readerId: { type: mongoose.Schema.Types.ObjectId, 
                ref: 'Profile', default: [] },
    readAt: { type: Date }
  }]

为了查询最新的通知,这是我写的查询:

GOAL 是检查 profile.id" DOES NOT 是否存在于 readBy 数组 中(这意味着该用户未阅读它)

const notifications = await Notification.find({
      receiver: profile.id,    // this works 
      readBy: {                // but, adding this returns an empty array 
        $elemMatch: {
          readerId: { $ne: profile.id }
        }
      }
})

非常感谢您的帮助,在这里停留了几天。

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    我认为这比我们尝试做的要容易。

    如果你想知道元素是否在数组中,那么,查询寻找它。如果查询为空,则表示不存在,否则为存在。

    看看这个example

    是一个简单的查询,只检查用户profile.id是否收到并阅读了一个文档。

    db.collection.find([
      {
        "receiver": profile.id,
        "readBy.readerId": profile.id
      }
    ])
    

    请检查输出是否符合预期或我误解了您的请求。

    mongoose 你可以使用这个:

    var find = await model.find({"receiver":1,"readBy.readerId":1}).countDocuments()
    

    它将返回与查询匹配的文档数。

    编辑以获取数组中不存在readerId 的文档:

    这里只需要添加$ne操作符

    db.collection.find([
      {
        "receiver": profile.id,
        "readBy.readerId": {
          "$ne": profile.id
        }
      }
    ])
    

    你可以查看这个here

    【讨论】:

    • 感谢您的回答,但您在这里错过了一件重要的事情,我希望 readerId 不在 readBy 数组中。你能更新一下答案吗?
    • 非常感谢,它成功了,mongo 游乐场是我不知道的。它令人惊叹且非常有用。
    猜你喜欢
    • 2013-03-04
    • 2014-05-21
    • 2014-05-19
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 2019-08-09
    相关资源
    最近更新 更多