I have three collections A, B, and C.
I want to make a nested populate with
A.findById(id).populate({
path: 'B_docs',
populate: {
path: 'C_doc'
}
})
The problem is that the document in the C
collection might not exist, so I end up with a document from A
with multiple documents from B
, but some of the documents in B
has a reference to documents in C
, which might have been deleted.
How do I make sure that I only include those B
documents where the referenced C
document still exists?
Of course I could just use
a_doc.b_docs.filter(b_doc => !!b.c_doc)
but I want to remove these docs (since they are invalid in my context) directly with Mongoose.
I think it's not possible with the built in populate function because mongoose query the database and build the result in the following order:
B_docs
C_doc
attributeWhen Mongoose could find out C is missing all of the B docs are already populated, if Mongoose could filter the document based on your condition, that would be executed in node level, so you can do the same with the mentioned code part:
a_doc.b_docs.filter(b_doc => !!b.c_doc)
A possible solution could be an aggregation, with $project
and $filter
it should be possible