I have the following model:
我有以下模型:
var followerSchema = new Schema({
id_follower: {type: Schema.Types.ObjectId, ref: 'Users'},
id_post: {type: Schema.Types.ObjectId, ref: 'Posts'}
});
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.
我希望能够找到所有的跟随者的帖子。当我使用find时,它返回的当然是同一个post的倍数,因为多个用户可以使用同一个post。
So I tried to use distinct, but I have the feeling the "populate" does not work afterwards.
所以我尝试使用不同的,但是我有一种感觉,“填充”在之后不会起作用。
Here is my code:
这是我的代码:
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.
它只返回post的数组,没有填充。
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.
我是mongoDB的新手,但是根据mongoose的文档,“不同”方法应该返回一个查询,就像“查找”方法一样。在查询中,可以执行“populate”方法,这样我就不会看到哪里出错了。
I also tried to use the .distinct() method of the query, so then my code was like this:
我还尝试使用查询的.distinct()方法,所以我的代码是这样的:
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...
在这种情况下,它可以工作,但是在mongoose的文档中,当您在查询中使用不同的方法时,您需要提供一个回调函数,因此在我的日志中,到处都是错误。一个解决方案是有一个虚拟回调函数,但我想避免……
Does anybody has an idea why the first attempt is not working? And if the second approach is acceptable by providing a dummy callback?
有人知道为什么第一次尝试行不通吗?如果第二种方法可以通过提供一个虚拟回叫来接受呢?
1 个解决方案
#1
5
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);
});
});
#1
5
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);
});
});