【问题标题】:Mongoose: multi: true for a projection update doesn't work?Mongoose: multi: true 对于投影更新不起作用?
【发布时间】:2022-02-18 03:13:43
【问题描述】:

具有以下结构的文档:

{
   _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Story' },
   notifications: [{
      story: {
         _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Story' },
         video_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Video' }
      },
      video: {
         _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Video' },
         video_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Video' }
      },
      type: { type: String },
      read: { type: Number, default: 0 }, // 0 - Unread, 1 - read
      ts: { type: Date, default: Date.now }
    }]
}

我正在尝试将read 元素等于0 的所有通知标记为已读,但出于任何原因,我的代码只修改了第一个通知:

mongoose.model('User').update({ _id: user_id, 'notifications.read': 0 }, { $set: { 'notifications.$.read': 1 }}, { multi: true });

我是否正确使用了multi: true

更新

我会说我正在尝试做的事情,使用 placeholder 没有任何意义,因为正如文档所说:

$。充当占位符,在更新中更新与查询条件匹配的第一个元素。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    当你使用{ _id: user_id, 'notifications.read': 0 }这个更新文档时,它只会找到一个文档,因为你是通过_id查询的。

    您应该改用{'notifications.read': 0 }

    【讨论】:

    • 测试你的答案,即使我删除了_id: user_id,它也会不断更新我的第一个通知
    • 您是使用multi:true 更新notifications 子文档还是主文档?
    • 正如我在描述中指定的,我正在尝试更新所有 read 属性等于 0 的子文档
    • multi:true 无法更新子文档。它更新所有符合条件的主要文档。在您的情况下,我认为通知是主要文件。 docs.mongodb.com/manual/reference/method/db.collection.update/…
    【解决方案2】:

    您必须使用$ 占位符,但要在一个查询中修改多个嵌入文档,还必须使用arrayFilters,指定here。此外,您不必使用multi: true

    在你的情况下,它看起来像这样:

    mongoose.model('User').updateOne(
        { _id: user_id },
        { $set: { 'notifications.$[element].read': 1 } },
        { arrayFilters: [{ 'element.read': 0 }] }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 2023-02-15
      相关资源
      最近更新 更多