And*_*len 11 mongoose mongodb node.js
我有以下型号:
var followerSchema = new Schema({
id_follower: {type: Schema.Types.ObjectId, ref: 'Users'},
id_post: {type: Schema.Types.ObjectId, ref: 'Posts'}
});
Run Code Online (Sandbox Code Playgroud)
我希望能够找到关注者列表的所有帖子.当我使用find时,它当然会多次返回同一个帖子,因为多个用户可以关注相同的帖子.
所以我尝试使用distinct,但我觉得"填充"后来不起作用.
这是我的代码:
followerModel
.distinct('id_post',{id_follower:{$in:followerIds}})
.populate('id_post')
.sort({'id_post.creationDate':1})
.exec(function (err, postFollowers) {
console.log(postFollowers);
})
Run Code Online (Sandbox Code Playgroud)
它只返回帖子的数组,并且没有填充.
我是mongoDB的新手,但根据mongoose的文档,"distinct"方法应该返回一个查询,就像"查找"方法一样.在查询中,您可以执行"填充"方法,因此我看不出我做错了什么.
我也尝试使用查询的.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);
})
Run Code Online (Sandbox Code Playgroud)
在这种情况下它可以工作,但是在mongoose的文档中,当你在查询中使用distinct方法时,你需要提供一个回调函数,所以在我的日志中我总是得到错误.一个解决方法是有一个虚拟回调函数,但我想避免...
有没有人知道为什么第一次尝试不起作用?如果第二种方法可以通过提供虚拟回调来接受?
考虑到目前猫鼬缺乏支持,这是否是正确的方法?
followerModel
.find({id_follower:{$in:followerIds}})
.distinct('id_post',function(error,ids) {
Posts.find({'_id':{$in : ids}},function(err,result) {
console.log(result);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6796 次 |
| 最近记录: |