Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random document from a collection in 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.

like image 946
user1680104 Avatar asked Feb 01 '13 10:02

user1680104


People also ask

What does .save do 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.

What is findById in Mongoose?

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.

What does findById return Mongoose?

Return value findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .


2 Answers

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.

like image 93
matthewtole Avatar answered Sep 22 '22 01:09

matthewtole


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     });  }); 
like image 30
Eat at Joes Avatar answered Sep 25 '22 01:09

Eat at Joes