如何更新猫鼬模式中另一个数组内的数组中的对象?

问题描述 投票:-1回答:1

在这里找到了很多类似这样的问题,但没有答案。

问题

假设我具有以下猫鼬模式:

const mySchema = new mongoose.Schema({
  sanePeoplesField: String,
  comments: [
    normalStuff: {type: Date, default: Date.now},
    damNestedAgain: [String]
  ]
})

所以回顾一下,damNested array位于模式的comments array内部。

如果我很幸运,并且想要更改normalStuff(数组内的obj),我会这样做:

mySchema.findOneAndUpdate({"comments._id": req.body.commentId},
{
    $push:
    {
      comments: { normalStuff: 12122020 } }
    }
})

这将使用新值更新normalStuff。

但是,我需要更新damNestedAgain中的字段,但不知道如何到达它!

问题

在我的示例中,如何更新嵌套数组damNestedAgain的嵌套数组?

arrays mongodb mongoose mongoose-schema
1个回答
0
投票
mySchema.findOneAndUpdate({"comments._id": req.body.commentId},
{
    $push:
    {
      "comments.$.damNestedAgain": req.body.commentId
    }
})

完成了技巧,谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.