Random document from a collection in Mongoose

后端 未结 6 2183
北恋
北恋 2020-12-02 23:45

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, b

6条回答
  •  难免孤独
    2020-12-02 23:58

    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.

提交回复
热议问题