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

115
Visualizações
How to loop through a nested array of objects in mongo and nodejs?

I have a collection of posts each of which look something like this:

{Post: 
    [ 
        id: 'post_id',
        postedBy: 'user_id',
        likes: [0: id: 'user_id', 1: id: 'user_id'],
        content: 'text here',
        comments: [0: {id: 'comment_id', text: 'text here', postedBy: 'user_id'},
                   1: {id: 'comment_id', text: 'text here', postedBy: 'user_id']
        image: {url: 'image url here'}
    ],
    [ 
        id: 'post_id',
        postedBy: 'user_id',
        likes: [0: id: 'user_id', 1: id: 'user_id'],
        content: 'text here',
        comments: [0: {id: 'comment_id', text: 'text here', postedBy: 'user_id'},
                   1: {id: 'comment_id', text: 'text here', postedBy: 'user_id']
        image: {url: 'image url here'}
    ],
}

I want to be able to find all the comments that were created by a specific user, across all of the posts .

I know I can find posts created by a specific user by doing something like:

const post = await Post.find({ postedBy: some user_id });

I also know that if I knew the index of the comment I was looking for I could do something like:

const comment = await Post.find({ comments[0].postedBy: some user_id })

But I am struggling to work out how I can loop through a nested array of indexed objects like this to find the data I need. TIA

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

0

From the docs I discovered the $elemMatch operator and with this I was able to access all posts that contained a comment written by a specific user like this:

const posts = await Post.find({
  comments: { $elemMatch: { postedBy: user_id } },
});

I could then map through the returned array to access the comments themselves like this:

const comments = posts.map((item) => item.comments);

Hope this might help somebody else some day

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