Random document from a collection in Mongoose

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));
};

Source: https://gist.github.com/3453567

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

Leave a Comment