![](/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.