我有以下查询从我的用户模式中返回一个随机用户:
UserSchema.statics.random = function(id,callback) {
this.count(function(err, count) {
if (err) {
return callback(err);
}
var rand = Math.floor(Math.random() * count);
this.findOne()
.where('_id').ne(id)
.where('last_active').gte(new Date(new Date().setDate(new Date().getDate()-3)))
.skip(rand)
.exec(callback);
}.bind(this));
};
但是有时它会返回NULL
-我认为这是因为它首先计算文档,然后应用过滤器来减少文档的数量,因此该rand
值可能高于可用的文档数量。
我似乎想不出有什么更好的方法来做到这一点?
我会运行上面的查询,计算文档然后使用.skip()
参数运行另一个查询吗?