我的MongoDB文档如下所示:
{_id: ObjectId("xxx"),
username: 'user',
active_courses: [
{'name': 'MongoDB',
'notes': [
{'title': 'Note title',
'note': 'Actual note content'}
]}
]
现在我需要更新标题为"注释标题"的注释对象。我该怎么做?
我试过以下几种,但都不起作用。
Student.findOneAndUpdate(
{username:req.body.username},
{$set: {'active_courses.$[course].notes.$[note]': req.body}},
{arrayFilters: [{'course.name': req.body.course},{'note.title': req.body.title} ]})
.then(result => {
res.status(200).json({message: 'Note saved!'})
})
顺便说一句,我不知道数组的索引,所以我不能使用active_courses[0]。注意…
感谢在这个问题上提供的任何帮助。谢谢
您可以将嵌入的文档定义为模式,这样mongoose就会自动为它们生成对象。有了这个id,你可以通过它的父文档访问并修改你的子文档,如下所示:
var doc = parent.children.id(_id);
Mongoose子文档