This question already has an answer here:
I don't know when to use ref
in schema, but recently I started to use it as it looks clean. Below is a working example.
const UserSchema = new Schema({
credit: {
type: Schema.Types.ObjectId,
ref: 'Credit'
}
})
I will just use populate like so
const response = await User.find({}).populate('Credit').exec()
But in my other case, I have to use $lookup
as in other controllers the previous dev have used aggregation.
const response = await Job.aggregate([
{
$match: queryObj
},
{
$lookup: lookupObj
},
{
$lookup: {
from: 'credit',
localField: ??
foreignField: ??
as: 'credit'
}
}
])
as you can see the code above, I have to slip in this extra $lookup
{
$lookup: {
from: 'credits',
localField: ??, //no idea what this should be.
foreignField: '_id'
as: 'credits'
}
}
But it still doesn't work. I got a credit property as an empty array.
from
argument to lookup. This will typically becredits
in plural. But you can always dofrom: Credit.collection.name
to get the true name from the model where already loaded. – Neil Lunn May 20 '18 at 7:38s
to makecredit
ascredits
still getting empty array. – Hoknimo May 20 '18 at 7:40ObjectId
values that actually match. If you can do apopulate()
and get a result then it's always 1. Ifpopulate()
returns no result then it's 2. No other cause. AndlocalField
is of coursecredit
andforeignField
is_id
. – Neil Lunn May 20 '18 at 7:42ObjectId
, unless in $lookup you need that. – Hoknimo May 20 '18 at 7:52