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

210
Visualizações
How can I populate a reference within a reference with Mongoose and MongoDB

I have Posts which contains a comments reference, the comments have a user reference. I want to create a method in which I can get the user with their comment.

    Post: [comment_id, comment_id]
    Comment: [user_id]

The following is what I have so far:

postRouter.get('/:postId/comments', (req, res, next) => {
  Post.findOne({ _id: req.params.postId })
    .populate('comments')
      // this does not work
    .populate('comments.user')
    .exec((err, comments) => {
      if (err) {
        res.status(500);
        return next(err);
      }
      return res.status(200).send(comments);
      // returns
      // { 
      // "_id": "1234567", 
      // "comments": [ { "_id": "891011", "body": "hello world", "user": "456789" }]
      //  }
    });
});

As stated before where I get the "user" I would like to populate it with the user document. Is this possible?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Yes, it's possible. You can do it like this:

Post.findOne({ _id: req.params.postId }).populate([
  { 
    path: 'comments', 
    populate: [{ path: 'user' }] 
  }
]);
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