如何使用mongoose更新mongodb集合中数组的子对象?

7vhp5slm  于 2022-12-27  发布在  Go
关注(0)|答案(1)|浏览(226)

我是mongodb/mongoose的初学者,我有一个mongoose文档:

const MySchema = mongoose.Schema({
  name: {
    type: String,
    minLength: 5,
    maxlength: 100,
    required: true
  },
  children: [{
    name: {
      type: String,
      minLength: 10,
      maxlength: 200,
      required: true
    },
  }],
}],

它保存了这样一个文档:

{
  "_id" : ObjectId("63a4bde8680e26987e8abd1f"),
  "name" : "parent 1",
  "children" : [{
      "name" : "child 1",
      "_id" : ObjectId("63a94a4a1baa3d5bfdc22fb4")
    },
    {
      "name" : "child 2",
      "_id" : ObjectId("63a94a4a1baa3d5bfdc22fb4")
    }
  ]
}

如何更新给定objectId的单个子对象(例如:63 a94 a4 a1 baa 3d 5 bfdc 22 fb 4)使用 Mongoose ?
我回忆起父元素,但不知道如何更新单个子元素

let parent = await Manager.getParent(parentId);
  let documentToUpdate = {
    question: question,
    questionType: questionType,
    answers: answers
  }
...
d8tt03nd

d8tt03nd1#

您可以使用positional operator - $执行此操作,如下所示:

MyModel.updateOne({
  "name": "parent 1",
  "children._id": "63a94a4a1baa3d5bfdc22fb4"
},
{
  "$set": {
    "children.$.name": "new name"
  }
})

Working example

相关问题