簡體   English   中英

更新 MongoDB 文檔數組字段中的所有對象

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

我正在嘗試做的事情

我正在嘗試使用 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,
        }
      );

有沒有辦法簡單地做到這一點?

可以使用all positional operator $[] ,您可以這樣做:

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

有關更多詳細信息,您可以在此處查看

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM