mongoose盘点文件

我有下面的查询从我的用户模式返回一个随机的用户:

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我想这是因为它先计算文档,然后使用filter来减less文档的数量,这样rand值可能会高于可用文档的数量。

我似乎无法想象这样做会更好吗?

我会运行上面的查询,计数文档然后运行另一个查询与.skip()参数?

你不想要findOne() ,你只需要find()limit(1).skip(rand) 。 正如@WiredPrairie所评论的,您还需要确保您的.find查询与您的.find查询相同,以便最大限度地减less跳过结尾的可能性。 如果logging在countfind之间被删除,仍然是可能的。 这是一个未经testing的片段:

 UserSchema.statics.random = function(id, callback) { var conditions = { _id: {$ne: id}, //not sure WTF you are trying to do here, but consider moment.js // Users must be active within the last 3 days last_active: new Date(new Date().setDate(new Date().getDate()-3)) }; this.count(conditions, function(err, count) { if (err) { return callback(err); } var rand = Math.floor(Math.random() * count); this.find(conditions).limit(1).skip(rand).exec(callback); }.bind(this)); };