Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda