从mongoose中获取非空数据[duplicate]

[英]Fetching not null data from mongoose populate [duplicate]


This question already has an answer here:

这个问题已经有了答案:

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

我有两个mongodb集合Sparks和sparksteam,它们使用mongoose填充函数连接在一起

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. ?

在获取数据时,它还会获得null值,这是sparks集合中不可用的_id。如何只检索那些_id不为空的对象,即如何使其完全忽略空值。吗?

1 个解决方案

#1


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.

运行填充查询时,在内部运行findById()函数并返回所有数据。但是,当它找不到匹配该_id的任何文档时,它将返回null对象。

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

    你可以用_过滤你的最终结果。lodash库的过滤器。链接:https://lodash.com/docs/4.17.4 #过滤器

    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.
    2. 更新包含图书引用的主模式,并在删除一本书时删除引用。您可以使用主模式上的钩子来实现这一点。

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

    someSchema。发布(“删除”、函数(doc){//更新您的文档在这里});

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2017/01/09/13cef5960b9610093be97562223418a8.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告