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