简体   繁体   English

更新 MongoDB 文档数组字段中的所有对象

[英]Update all objects in a MongoDB document array field

What I'm trying to do我正在尝试做的事情

I am trying to update all objects inside a field array in a MongoDB document using mongoose.我正在尝试使用 mongoose 更新 MongoDB 文档中的字段数组内的所有对象。

What I have我有的

User document用户文件

{
 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!"
  },
 ]
}

What I want to have我想拥有的

{
 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
  },
 ]
}

I am working with mongoose which right now I am using the findByIdandUpdate method.我正在使用 mongoose,现在我正在使用findByIdandUpdate方法。 I tried using a method to do this but it just failed.我尝试使用一种方法来做到这一点,但它失败了。

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,
        }
      );

Is there a way to do this simply?有没有办法简单地做到这一点?

It can be possible using all positional operator $[] , you can do this:可以使用all positional operator $[] ,您可以这样做:

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

For more details, you can check here .有关更多详细信息,您可以在此处查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM