0

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!

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.