![](/img/trans.png)
[英]Update mongodb document that has multiple arrays of embedded documents using mongoose
[英]How to update embedded arrays/objects in MongoDb with mongoose?
我的 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].notes ...
感谢您对此问题的任何帮助。 谢谢!
您可以将嵌入的文档定义为模式,这样 mongoose 会自动为它们生成一个 objectid。 使用该 ID,您可以通过其父文档访问并修改您的子文档,如下所示:
var doc = parent.children.id(_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.