【问题标题】:How to update an object inside an array inside another array in a mongoose schema?如何更新猫鼬模式中另一个数组内的数组内的对象?
【发布时间】:2020-08-02 00:13:51
【问题描述】:

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

问题

假设我有以下猫鼬模式:

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】:
    mySchema.findOneAndUpdate({"comments._id": req.body.commentId},
    {
        $push:
        {
          "comments.$.damNestedAgain": req.body.commentId
        }
    })
    

    成功了,谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2021-12-28
      • 2016-04-23
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多