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

问题描述

我想做什么

我正在尝试使用 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
        }
      );

有关详细信息,您可以查看here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...