简体   繁体   English

如何使用猫鼬更新 MongoDb 中的嵌入式数组/对象?

[英]How to update embedded arrays/objects in MongoDb with mongoose?

My MongoDB document looks like this:我的 MongoDB 文档如下所示:

  {_id: ObjectId("xxx"),  
   username: 'user',  
   active_courses: [  
        {'name': 'MongoDB',  
         'notes': [  
           {'title': 'Note title',  
            'note': 'Actual note content'}  
       ]}  
    ]  

And now I would need to update the notes Object with title 'Note title'.现在我需要更新标题为“注释标题”的注释对象。 How can I do this?我怎样才能做到这一点?

I've tried the following but it doesn't work.我已经尝试了以下但它不起作用。

 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!'}) })

And BTW I do not know the indexes of the arrays so I can't use active_courses[0].notes...顺便说一句,我不知道数组的索引,所以我不能使用 active_courses[0].notes ...

Appreciate any help with this issue.感谢您对此问题的任何帮助。 Thanks!谢谢!

You could define your embedded documents as a schema, this way mongoose automatically generates an objectid for them.您可以将嵌入的文档定义为模式,这样 mongoose 会自动为它们生成一个 objectid。 With that id, you could access and then modify your subdocument via its parent like this:使用该 ID,您可以通过其父文档访问并修改您的子文档,如下所示:

var doc = parent.children.id(_id);

Mongoose subdocuments猫鼬子文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM