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
You can use aggregate:
User.aggregate([
{$match: {gender: "male"}},
{$sample: {size: 10}}
], function(err, docs) {
console.log(docs);
});
Or you can use npm package https://www.npmjs.com/package/mongoose-simple-random
User.findRandom({gender: "male"}, {}, {limit: 10}, function(err, results) {
console.log(results); // 10 elements
});