Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

407
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!