Friday, 19 May 2017

Filter documents with invalid reference in Mongoose populate

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.



via Jamgreen

No comments:

Post a Comment