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

324
Visualizações
Why does my mongodb nodejs driver query on aggregate $lookup not return results as expected

I have two collections: users and roles

The users have an array of roles assigned to them:

{
    _id : 61582a79fd033339c73ee290
    roles:[615825966bc7d715021ce8fc, 615825966bc7d715021ce8fd]
}

roles:

[
   {
     _id: 615825966bc7d715021ce8fc
     name: 'user',
   },
   {
     _id: 615825966bc7d715021ce8fd
     name: 'admin',
   },
]

As you can see the user has an array of object ids that correspond to the roles.

I have a $lookup aggregate query where I'm trying to return all users with the roles populated:

dbManager.aggregate = async () => {
    let a = dbInstance.collection('users').aggregate(
        [
            {
                $lookup:
                {
                    from: 'roles',
                    localField: 'roles',
                    foreignField: '_id',
                    as: 'user_roles'
                }
            }
        ]
    )
    console.log('a:::::::', a)
}

When I run this query: dbManager.aggregate(), I get a very big object and I don't see the user information anywhere nor how to extract it. According to the documentation, this should return the information I'm querying. Here's the first few fields of what it returns as I don't want to overwhelm with the huge object:

AggregationCursor {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
 [Symbol(kCapture)]: false,
 [Symbol(topology)]: Topology {
    _events: [Object: null prototype] {
      topologyDescriptionChanged: [Array],
    }
  ...
}

What am I doing wrong?

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

0

Apparently I have to call .toArray which returns a promise that resolves the data:

dbManager.aggregate = async () => {
    let a = await dbInstance.collection('users').aggregate(
        [
            {
                $lookup:
                {
                    from: 'roles',
                    localField: 'roles',
                    foreignField: '_id',
                    as: 'user_roles'
                }
            }
        ]
    )
     .toArray().then(data => data)
     .catch(e => console.log(e))
    console.log('a:::::::', a)
}

It kind of sucks that nowhere on the page does it say to do this on the MongoDB documentation but glad I could find a solution!

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