An attempt to fill in a mongoose only if ref is not equal to zero does not work

I am trying to get a list of books with their copyright information.

Some users have been deleted, and therefore they no longer have the db document, so their information is null.

I try to pull out books ONLY if their creators still exist.

This is my code:

Book.find({_creator:{$ne:null}}).populate( { path: '_creator', match: { _id: { $ne: null }} }) .exec(function (err,books) { if(err) throw err; if(books) { res.send(books) } }) 

This is what it returns:

  [ { "_id":"55d98e6a4de71010099c59eb", "dateOfCreation":"2015-08-23T09:12:10.095Z", "_creator":null, "__v":0, "coverUrl":"cover14403211323926quv.png", "description":"asdasd", "name":"asdasd" } ] 

Note that the _creator field is null. Why is this?

+4
source share
1 answer

you need to understand the execution order of your code:

  • mongoose retrieves all the books from the database, where {_creator:{$ne:null}} . Mongo only looks at the link inside the book collection to determine which documents to return. Your book still has a link to the author, and Mongo does not notice that there is no corresponding author in the collection of authors, so your book is uploaded.

  • mongoose fills in all returned results: therefore, it downloads authors from the Authors collection and replaces links to real objects. For your book, he does not find a suitable author, so he puts null .

That is why you are ending your list of results.

Mongo does not support joins, so you cannot execute a query that includes data from more than one collection. Filling out is just a way to replace the links in your resulting list with real data, you can never use populated data as part of your where clauses.

To solve the problem, you can:

  • filter the final list of results in JS code, for example. with _.filter library lodash.
  • update all your books and delete the link when you delete the author. You can use hooks on Author-Schema for this.

AuthorSchema.post('remove', function(doc) {// update your books here});

+5
source

All Articles