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

126
Visualizações
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 à 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