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 | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
Mongoose | findById() Function The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command. Installation of mongoose module: You can visit the link Install mongoose module. You can install this package by using this command.
Return value findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .
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.
If you are not wanting to add "test like" code into your schema, this uses Mongoose queries.
Model.count().exec(function(err, count){    var random = Math.floor(Math.random() * count);    Model.findOne().skip(random).exec(     function (err, result) {        // result is random     });  }); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With