Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

416
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda