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

查看:20
本文介绍了来自 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.

推荐答案

我在 GitHub Gist 中发现了这个 Mongoose Schema 静态函数,它应该可以实现您的目标.它计算集合中的文档数,然后在跳过随机数量后返回一个文档.

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 I modified the code a bit to make it more readable.

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

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