node.js - 更新数组mongodb中的多个元素

标签 node.js mongodb mongoose mongoose-schema

当日期大于特定值时,我想将 chargeList isDelete 属性更新为 true。我的架构如下。

{
   "chargeList": [
     { 
         "date": ISODate("2013-06-26T18:57:30.012Z"),
         "price": "123",
         "isDelete": false

     },
     { 
         "date": ISODate("2013-06-27T18:57:30.012Z"),
         "price": "75",
         "isDelete": false

     }
   ]
 }

架构如下。

var ChargeListSchema= new Schema({
    date:  { type: Date , default: Date.now  },
    price: { type: String, required: false },
    isDelete: { type: Boolean, default: false }
});

var ScheduleChargeSchema = new Schema({

  chargeList:[ChargeListSchema]


  });

我尝试了以下代码,但它只更新 chargeList 数组中匹配的第一个元素。

 Model.update(
  {
    "_id": 1,
    "chargeList": {
      "$elemMatch": {
        "date": {
           $gt:  ISODate("2013-06-26T18:57:30.012Z")
        }
      }
    }
  },
  {
    "$set": { "chargeList.$.isDelete": true }
  }
)

最佳答案

您需要使用$[] all positional operator更新数组中的多个元素

Model.update(
  { "_id": 1, "chargeList.date": { "$gt":  ISODate("2013-06-26T18:57:30.012Z") }},
  { "$set": { "chargeList.$[].isDelete": true } }
)

关于node.js - 更新数组mongodb中的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51279886/

相关文章:

javascript - `~`在javascript中是什么意思

Node.js:递归要求和导出

javascript - Passport deserializeUser() 永远不会通过 Axios http 请求调用

arrays - mongodb跨文档查找数组中的重复项

javascript - Mongoose 子文档与嵌套模式

mysql - Mongoose/Mongodb 迁移到 MySQL

node.js - Mongoose - 使用单个集合的多个模式

MongoDB 警告查询未使用索引

mongodb - 如何为所有文档生成唯一字段

javascript - 返回 promise 链中引用的数据