【问题标题】:Mongoose updateMany() not working in nested modelMongoose updateMany()在嵌套模型中不起作用
【发布时间】:2021-09-03 19:56:02
【问题描述】:

我有一个名为 Chatroom 的猫鼬模型,其结构如下:

[
  {
    _id: 60cd9816b9326c5cb40ca24c,
    chat_history: [
      {
        read_flag: 0,
        receiver_id: "60cc83b8b0ebb52f43278b1b"
      },
      {
        read_flag: 0,
        receiver_id: "60cc839db0ebb5b9f3278b1a"
      }
    ]
  },
  { 
    _id: 60cd9816b9326c5cb40ca24c,
    chat_history: [
      {
        read_flag: 0,
        receiver_id: "60cc83b8cccbb52f43278b1b"
      },
      {
        read_flag: 0,
        receiver_id: "60cc839db0ebamskf3278b1a"
      }
    ]
  }
]

我正在尝试更新 read_flag: 1 给定不同对象的receiver_id。 到目前为止,我有:

Chatroom.updateMany(
        { "chat_history.receiver_id": req.user._id },
        { $set: { "chat_history.$.read_flag": 1 } },
        { returnNewDocument: true }
        ).then((doc) => { console.log(doc) })

并尝试了在查询中放置位置过滤器 $ 的多种变体,但似乎没有任何效果。非常感谢任何关于我在这里做错了什么的见解。 MongoDB 中的嵌套更新文档非常混乱。

以下是我看到的 console.log 输出,但我的集合中的 read_flag 字段仍为 0。

{
  n: 1,
  nModified: 1,
  opTime: {
    ts: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1624101030 },
    t: 31
  },
  electionId: 7fffffff000000000000001f,
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1624101030 },       
    signature: { hash: [Binary], keyId: [Long] }
  },
  operationTime: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1624101030 }        
}

【问题讨论】:

  • 你能说得更具体一点,“不工作”是什么意思吗?
  • read_flag 字段未更新为 1。为歧义道歉,让我将其添加到问题中。
  • 一个都没有,还是只有一个?位置运算符只应该更新每个匹配文档中的第一个。
  • 它们都没有改变。那么如何更新文档中的所有标志呢?

标签: node.js mongodb mongoose nested


【解决方案1】:

啊,天哪,我想我偶然发现了一个解决方案:

    Chatroom.updateMany(
        { 
            "chat_history.receiver_id": req.user._id.toString() 
        },
        { 
            "$set": { "chat_history.$[elem].read_flag": 1 } 
        },
        { 
            "arrayFilters": [{ "elem.read_flag": 0}], 
            "multi": true 
        }
        ).then((doc) => { 
            console.log(doc)
            return 
        })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-06
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2015-03-29
    • 2021-04-26
    相关资源
    最近更新 更多