简体   繁体   中英

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

My MongoDB document looks like this:

  {_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...

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. With that id, you could access and then modify your subdocument via its parent like this:

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

Mongoose subdocuments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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