简体   繁体   中英

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.

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:

  1. Fetch A by id
  2. Fetch every B docs by id from B_docs
  3. Fetch every C docs by id from B docs's C_doc attribute

When 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM