我有以下模型:
var followerSchema = new Schema({
id_follower: {type: Schema.Types.ObjectId, ref: 'Users'},
id_post: {type: Schema.Types.ObjectId, ref: 'Posts'}
});
我希望能够找到关注者列表的所有帖子。当我使用 find 时,它当然会多次返回同一个帖子,因为多个用户可以关注同一个帖子。
所以我尝试使用不同的,但我感觉“填充”之后不起作用。
这是我的代码:
followerModel
.distinct('id_post',{id_follower:{$in:followerIds}})
.populate('id_post')
.sort({'id_post.creationDate':1})
.exec(function (err, postFollowers) {
console.log(postFollowers);
})
它只返回帖子数组,并且没有填充。
我是 mongoDB 的新手,但根据 mongoose 的文档,“distinct”方法应该返回一个查询,就像“find”方法一样。在查询中,您可以执行“填充”方法,所以我看不出我做错了什么。
我还尝试使用查询的 .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);
})
在这种情况下它可以工作,但正如在猫鼬的文档中一样,当您在查询上使用不同的方法时,您需要提供回调函数,因此在我的日志中我到处都是错误。解决方法是有一个虚拟回调函数,但我想避免这种情况......
有人知道为什么第一次尝试不起作用吗?如果通过提供虚拟回调来接受第二种方法?