[英]How to update a child in an array in mongodb collection using mongoose?
I am a very beginner with mongodb/mongoose.我是 mongodb/mongoose 的初学者。 I have this mongoose document:我有这个 mongoose 文档:
const MySchema = mongoose.Schema({
name: {
type: String,
minLength: 5,
maxlength: 100,
required: true
},
children: [{
name: {
type: String,
minLength: 10,
maxlength: 200,
required: true
},
}],
}],
that saves a document like this:保存这样的文档:
{
"_id" : ObjectId("63a4bde8680e26987e8abd1f"),
"name" : "parent 1",
"children" : [{
"name" : "child 1",
"_id" : ObjectId("63a94a4a1baa3d5bfdc22fb4")
},
{
"name" : "child 2",
"_id" : ObjectId("63a94a4a1baa3d5bfdc22fb4")
}
]
}
how can I update a single child given the objectId (ex: 63a94a4a1baa3d5bfdc22fb4) using mongoose?如何使用 mongoose 更新给定 objectId(例如:63a94a4a1baa3d5bfdc22fb4)的单个子项?
I recall the parent but I don't kbnow how to update a single child element我记得父元素,但不知道如何更新单个子元素
let parent = await Manager.getParent(parentId);
let documentToUpdate = {
question: question,
questionType: questionType,
answers: answers
}
...
You can do it with positional operator - $
, like this:您可以使用位置运算符 - $
来做到这一点,如下所示:
MyModel.updateOne({
"name": "parent 1",
"children._id": "63a94a4a1baa3d5bfdc22fb4"
},
{
"$set": {
"children.$.name": "new name"
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.