猫鼬和文件填充 [英] mongoose distinct and populate with documents

查看:76
本文介绍了猫鼬和文件填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:

var followerSchema = new Schema({
    id_follower: {type: Schema.Types.ObjectId, ref: 'Users'},
    id_post: {type: Schema.Types.ObjectId, ref: 'Posts'}
});

我希望能够找到所有关注者列表的帖子.当我使用find时,它当然会多次返回同一条帖子,因为多个用户可以关注同一条帖子.

I want to be able to find all posts for a list of followers. When I use find, it returns me of course multiple times the same post as multiple users can follow the same post.

因此,我尝试使用distinct,但是我觉得填充"此后将无法工作.

So I tried to use distinct, but I have the feeling the "populate" does not work afterwards.

这是我的代码:

followerModel
    .distinct('id_post',{id_follower:{$in:followerIds}})
    .populate('id_post')
    .sort({'id_post.creationDate':1})
    .exec(function (err, postFollowers) {
        console.log(postFollowers);
    })

它只返回我的帖子数组,而没有填充.

It only returns me the array of the posts, and it is not populated.

我是mongoDB的新手,但是根据mongoose的文档,"distinct"方法应返回查询,就像"find"方法一样.并且在查询中,您可以执行填充"方法,这样我就看不到我在做什么错了.

I am new to mongoDB, but according to the documentation of mongoose, the "distinct" method should return a query, just as the "find" method. And on a query you can execute the "populate" method, so I don't see what I am doing wrong.

我还尝试使用查询的.distinct()方法,因此我的代码如下:

I also tried to use the .distinct() method of the query, so then my code was like this:

followerModel
    .find({id_follower:{$in:followerIds}})
    .populate('id_post')
    .distinct('id_post')
    .sort({'id_post.creationDate':1})
    .exec(function (err, postFollowers) {
        console.log(postFollowers);
    })

在这种情况下,它可以工作,但是像在猫鼬的文档中一样,当您对查询使用不同的方法时,您需要提供一个回调函数,因此在我的日志中,我到处都是错误.一种解决方法是拥有一个虚拟的回调函数,但我想避免这种情况……

In that case it works, but as in the documentation of mongoose you need to provide a callback function when you use the distinct method on a query, and so in my logs I get errors all over. A workaround would be to have a dummy callback function, but I want to avoid that...

有人知道为什么第一次尝试不起作用吗?并且通过提供虚拟回调是否可以接受第二种方法?

Does anybody has an idea why the first attempt is not working? And if the second approach is acceptable by providing a dummy callback?

推荐答案

考虑到当前在猫鼬中缺乏支持,这是否是正确的方法?

Would this be the right way considering the current lack of support in mongoose?

followerModel
.find({id_follower:{$in:followerIds}})
.distinct('id_post',function(error,ids) {
   Posts.find({'_id':{$in : ids}},function(err,result) {
     console.log(result);
   });
});

这篇关于猫鼬和文件填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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