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

129
Vistas
How to map through the results of a MongoDB aggregate query in React

I have a MongoDB aggregate query which uses two lookups. The data is being retrieved correctly and output as I would expect when I console log it. However, I've spent bloody hours trying to access the nested arrays and objects, with no luck so far and I need some help, please.

This is my query:

const pipeline = [
    {
        '$lookup': {
            'from': 'posts',
            'localField': 'likedThing',
            'foreignField': 'id',
            'as': 'likedPost'
        }
    }, {
        '$lookup': {
            'from': 'users',
            'localField': 'userId',
            'foreignField': 'id',
            'as': 'userData'
        }
    }, {
        '$match': {
            'userId': userId
        }
    }
  ]

const postdata = await db.collection('likes').aggregate(pipeline).toArray();

If we console.log(postdata):

[
    {
    _id: '0_m5wSs6WGuAtrfmQuHJI',
    likedThing: '617ba5d6df45df5616becb21',
    userId: 'GYmLSp0fL9dTuJvEuJVL0vsBYnX2',
    likedPost: [ [Object] ],
    userData: [ [Object] ]
},
{
    _id: 'Xs6GakQ_FVIbYUhtN_-e8',
    likedThing: '617ba277df45df5616becb20',
    userId: 'GYmLSp0fL9dTuJvEuJVL0vsBYnX2',
    likedPost: [ [Object] ],
    userData: [ [Object] ]
 }]

I then log the likedPost array/object => console.log('likedPost: ',postdata[0].likedPost) which gives me:

likedPost:  [
    {
    _id: new ObjectId("617ba5d6df45df5616becb21"),
    userId: 'i3PYKSLvAcfEd1JdNSEh7qk8NJx1',
    post: 'some post.',
    }
 ]

I pass 'postdata' to a component to map through it:

<Feed postdata={postdata}/>

And in the Feed component I try to access 'post' value in the nested 'likedPost' array/object and I can't. Given the output of the console logs it seems to me to access to post value I should do the following:

{postdata.map((postdata, i) => (
    <Card
        key={i}
        post={postdata.likedPost[0].post}
        ...
    />
))}

But I get 'Cannot read properties of undefined (reading 'post')' even though this console log outputs the post:

console.log('likedPost.post: ',postdata[0].likedPost[0].post)

I think it's something to do with likedPost being an array, hence the [0] above, containing an object. How do I access the 'post' key value within the likedPost array/object in my Feed component, please?

about 4 years ago · Juan Pablo Isaza
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