Search code examples
javascriptarraysobjectmongoosemutation

Mongoose update an object in a nested array of object inside a collection


i have this code :

const updateComment = async (req, res) => {
  try {
    const post = await Post.findById(req.body.postId);
    const comment = post.comments.find(
      (comment) => comment.id === req.body.commentId
    );

    res.status(200).json(comment);
  } catch (err) {
    console.log(err);
    res.status(500).json(err);
  }
};

since i can't use mongoose find or findById because it's not a collection, i used javascript find method to find a specific comment, but since i can't also use updateOne, how can i update the comment body?

i tried this :

comment.body = req.body.newCommentBody;

but it doesn't work, how to mutate the object in the database?


Solution

  • Depends if you're using unique commentId across all database (like ObjectId). Then you can use updateOne to search by comment id and use positional operator $ like this:

    await Post.updateOne(
    {"comments.id" : req.body.commentId}, 
    {"comments.$.body": req.body.newCommentBody}
    ) 
    

    But this way you won't get comment to send in res. You can also find post, update in place and send back to db:

    const post = await Post.findById(req.body.postId)
    const comment = post.comments.find(
          (comment) => comment.id === req.body.commentId
        );
    comment.body = req.body.newCommentBody
    await post.save()
    
     res.status(200).json(comment);
    

    I'm not sure if .findById() returns array or single doc, if array you have to add [0] of course.