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

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

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 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