来自Mongoose集合的随机文档 [英] Random document from a collection in Mongoose

查看:651
本文介绍了来自Mongoose集合的随机文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 Schema.statics.random 函数,它从集合中获取一个随机元素。我知道有一个本机MongoDB驱动程序的例子,但是我无法在Mongoose中使用它。

I want to create a Schema.statics.random function that gets me a random element from the collection. I know there is an example for the native MongoDB driver, but I can't get it working in Mongoose.

推荐答案

我找到了这个Mongoose Schema静态函数在GitHub Gist中,它应该实现你所追求的目标。它会计算集合中的文档数量,然后在跳过随机数量后返回一个文档。

I found this Mongoose Schema static function in a GitHub Gist, which should achieve what you are after. It counts number of documents in the collection and then returns one document after skipping a random amount.

QuoteSchema.statics.random = function(callback) {
  this.count(function(err, count) {
    if (err) {
      return callback(err);
    }
    var rand = Math.floor(Math.random() * count);
    this.findOne().skip(rand).exec(callback);
  }.bind(this));
};

资料来源: https://gist.github.com/3453567

NB 我修改了代码a让它更具可读性。

NB I modified the code a bit to make it more readable.

这篇关于来自Mongoose集合的随机文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆