【问题标题】:How to update an specific array's object inside another array in mongoose?如何在猫鼬中更新另一个数组中的特定数组对象?
【发布时间】:2020-08-12 22:12:03
【问题描述】:

我有一个这样的架构:

const NoteClusterSchema = new Schema({
   noteInfo: [{
        title: String,
        Description: String,
        authors:[{
          name: String, Id: String
        }]
   }],
   idGroup: String //this is the group of the people that are working on the proyect
}, {timestamps:true});

noteInfo 的一个例子是

noteInfo: [{
  title: "Hello",
  Description: "Hello World",
  authors:[
     {name: "Marcelo", id: "1234123123"},
     {name: "Pancho", id: "12341345344"}
  ]
}]

例如,如何在作者数组中更新“Marcelo”的名称? (假设如果用户更改了它的名称。我知道在这种特定情况下我可以只放置 _id,但在我的真实架构中它不是我想要更新的用户)

我想到了这样的事情:

await NoteClusterSchema.updateMany({idGroup: req.body.idGroup}, 
                {
                    noteInfo: {$push: {authors: {name: 
                    req.body.name}}}
             })

但是通过这种方式,它不会知道所有noteInfo数组中的哪一个更新或者它会创建一个新的authors数组,而更改noteInfo: {$push:$push: {noteInfo:只会创建一个新的noteInfo数组。

那么,如何使用 UpdateMany 方法更新另一个数组中的一个数组中的这个特定对象?

【问题讨论】:

标签: arrays mongodb mongoose mern


【解决方案1】:

使用 $set 选项的

findOneAndUpdate 应该可以解决您的问题:

NoteClusterSchema.findOneAndUpdate(
    {idGroup: req.body.idGroup},
    {$set: {"noteInfo.$[element].value": "YOUR_NEW_NAME" } },
    {
        arrayFilters: [{ "element.name": "Marcelo" }],
        new: true
    }
)

注意:您必须添加 arrayFilters 选项才能定位数组中的特定元素。

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 1970-01-01
    • 2020-08-02
    • 2021-12-28
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多