仅在ref不为null时尝试填充猫鼬-不起作用 [英] Trying to populate in mongoose only if ref is not null - not working

查看:74
本文介绍了仅在ref不为null时尝试填充猫鼬-不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取包含其作者信息的书籍清单.

I'm trying to get a list of books with their author information.

某些用户已被删除,因此他们在数据库中不再有文档,因此,他们的信息为空.

Some users were deleted and therefore they have not longer a document in the db, therefore, their info is null.

如果他们的创作者仍然存在,我只会尝试拉书.

I'm trying to pull books ONLY if their creators still exist.

这是我的代码:

  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)
        }
    })

这是返回的内容:

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

请注意,_creator字段为null. 这是为什么?

Notice that the _creator field IS null. Why is that?

推荐答案

您需要了解代码的执行顺序:

you need to understand the order of execution of your code:

  1. 猫鼬从数据库{_creator:{$ne:null}}中获取所有书籍. Mongo仅查看图书藏书中的参考资料来确定要退还哪些文件.您的书仍然引用了作者,而mongo不会注意到Authors集合中没有匹配的Author,因此已加载您的书.

  1. mongoose gets all books from the database where {_creator:{$ne:null}}. Mongo is only looking at the reference inside the books collection to determine which documents to return. Your book still has a reference to an author, and mongo will not notice that there is no matching Author in the Authors collection, so your book is loaded.

猫鼬正在填充所有返回的结果:因此它将从Authors集合中加载作者,并将引用替换为真实对象.对于您的书,找不到匹配的作者,因此将null放在此处.

mongoose is populating all returned results: so it is loading the authors from the Authors collection and replaces the references with the real objects. For your book it does not find a matching author, so it puts the null there.

这就是为什么您最终得到结果列表的原因.

Thats why you end up with your resultlist.

Mongo不支持联接-因此,您无法进行包含多个集合中的数据的查询.填充只是将结果列表中的引用替换为真实数据的一种方法,您永远不能将填充的数据用作where子句的一部分.

Mongo does not support joins - therefore you cannot do a query that includes data from more than one collection. Populate is just a way to replace references in your resultlist with real data, you can never use populated data as part of your where clauses.

要解决您的问题,您可以:

To solve your issue you can either:

  • 使用JS代码过滤最终结果列表,例如使用lodash库的_.filter.
  • 更新所有图书,并在删除作者时删除参考书目.您可以在Author-Schema上使用钩子.

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

这篇关于仅在ref不为null时尝试填充猫鼬-不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆