【问题标题】:Update all objects in a MongoDB document array field更新 MongoDB 文档数组字段中的所有对象
【发布时间】:2021-07-24 22:31:16
【问题描述】:

我要做什么

我正在尝试使用 mongoose 更新 MongoDB 文档中字段数组内的所有对象。

我有什么

用户文档

{
 id: <ObjectId>,
 ...
 notifications: [
  {
   commissionId: <ObjectId>
   commissioner: <ObjectId>
   date: ...
   description: "You have a new commission!"
  },
  {
   commissionId: <ObjectId>
   commissioner: <ObjectId>
   date: ...
   description: "You have a new commission!"
  },
 ]
}

我想要的东西

{
 id: <ObjectId>,
 ...
 notifications: [
  {
   commissionId: <ObjectId>
   commissioner: <ObjectId>
   date: ...
   description: "You have a new commission!"
   read: true // Add read field with a value of true
  },
  {
   commissionId: <ObjectId>
   commissioner: <ObjectId>
   date: ...
   description: "You have a new commission!"
   read: true // Add read field with a value of true
  },
 ]
}

我正在使用 mongoose,现在我正在使用 findByIdandUpdate 方法。我试过了 使用一种方法来执行此操作,但它失败了。

await User.findByIdAndUpdate(
        args.userId,
        {
          notifRead: true,
          $set: {
            "notifications.$.read": true, // FAIL "The positional operator did not find the match needed 
                                          // from the query."
          },
        },
        {
          new: true,
          runValidators: true,
        }
      );

有没有办法简单地做到这一点?

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

可以使用all positional operator $[],你可以这样做:

await User.update(
        args.userId,
        {
          $set: {
            "notifications.$[].read": true,                             
          },
        },
        {
          muti: true
        }
      );

更多详情可以查看here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    相关资源
    最近更新 更多