2

I have two mongodb collections Sparks and sparksteam, which are being joined using mongoose populate function

this is the code.

 Books.find({"user_id": "55006c36c30f0edc5400022d",$or: [{"status": 2}, {"status": 1}]}).sort({"order_date": -1}).populate({
         path: 'book_id',
         select: 'title _id user task_category create_date description end_date status ref_number order_date'
         }).exec(function (err, data) {

         console.log("Data found:" + data.length);
         data.forEach(function (check) {

             var obj = new Object();

         if (check.book_id !== null) {
                 obj._id =  check.book_id._id;
                 obj.title = check.book_id.title;
                 obj.description = check.book_id.description;
                 obj.ref_number = check.book_id.ref_number;
                 obj.user = check.book_id.user;
                 obj.task_category =check.book_id.task_category;
                 obj.create_date = moment.utc(check.create_date).format("DD-MM-YYYY HH:mm:ss");
                 obj.status = check.book_id.status;
                 obj.order_date = check.book.order_date;
                console.log(obj);
        }

Upon fetching the data, it is also getting null values as well, which are the _ids that are not available in the sparks collection. How do I retrieve only those objects whose _ids are not null, that is, how to make it completely ignore null values. ?

Ahsan Jamal
  • 218
  • 1
  • 3
  • 17

1 Answers1

2

When you run a populate query, internally it runs a findById() function and returns all the data. However, when it cannot find any document matching that _id, it returns the null object.

There is no way to query for non-null reference objects beforehand. But there are ways to filter out null values quickly.

  1. You can use filter your final result with _.filter of the lodash library. Link : https://lodash.com/docs/4.17.4#filter

    1. update the main schema containing the book reference and remove the reference whenever you delete a book. You can use hooks on the main Schema to do this.

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

Shreya Batra
  • 730
  • 1
  • 6
  • 15