mongoose update subdocument by id 1

mongoose update subdocument by id

//this method for add data to subdocument
BlogPost.findById(req.params.postId, function (err, post) {
    var subDoc =;
    subDoc = req.body; (err) {
        if (err) return res.status(500).send(err);

// alternative second method you can use this
BlogPost.findOneAndUpdate({_id: req.params.postId}, {$push:{ subDoc: req.body }}, (err, doc) => {
  	// do something here

Here is what the above code is Doing:
1. Find the blog post by its ID.
2. Find the comment by its ID.
3. Update the comment with the new data.
4. Save the blog post.
5. Send the updated blog post back to the user.

Similar Posts