I am trying to lookup a parent field by ID as part of an aggregation pipeline, but only certain fields have a parent.
so this code works fine when there is a parent, but breaks when there isn't:
//get parent info
{
'$lookup': {
"from": this.parentContentModel,
"localField": "parent",
"foreignField": "_id",
"as": "parent"
}
},
{'$unwind': { path: '$parent' } },
According to this it's fine if the lookup doesn't exist (though it doesn't work if the field name is empty or null, so I put in a placeholder):
//get parent info
{
'$lookup': {
"from": this.parentContentModel || 'noparent',
"localField": "parent",
"foreignField": "_id",
"as": "parent"
}
},
{'$unwind': { path: '$parent' } },
Adding this doesn't fix it though, because then I need to unwind it, which breaks if the field doesn't exist. (If i take out the unwind, then it works fine when theres no parent, but then things with parents are broken because they need to be unwound).
According to this you can just project an empty array if the value was null, but $project drops all the old fields:
{'$project': { parent: {'$ifNull': ['$parent', [ null ] ]}}},
So I tried using $addFields instead of $project, but it still broke things with no parent field:
{'$addFields': { parent: {'$ifNull': ['$parent', [ null ] ]}}},
With that line added, it still only works for docs with a parent, unless I remove $unwind
, which makes it only work for docs without a parent.