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.