Reputation: 190
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!
Upvotes: 0
Views: 57
Reputation: 68
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);
Upvotes: 1