Bruno Pigatto
Bruno Pigatto

Reputation: 67

Mongoose .populate random

Its possible to 'populate random' ?

Example

.populate({
    path: 'path',
    options: {limit: 2}
});  

"Example" always return the same 2 items. Always the last 2 items in the array.
Is it possible to return a random item using .populate()? How can it be made?

Upvotes: 1

Views: 183

Answers (1)

Taki
Taki

Reputation: 17654

user javascript' Math.random and Math.floor

The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

more details and examples : https://www.w3schools.com/js/js_random.asp

so to have a random limit between 1 and 20 :

var myLimit = Math.floor(Math.random() * (20 - 1) + 1);

.populate({
    path: 'path',
    options: {limit: myLimit}
}); 

EDIT

if you want to return 2 random items each time, use skip :

var myRandom = Math.floor(Math.random() * (20 - 1) + 1);

.populate({
    path: 'path',
    options: {limit: 2, skip:myRandom}
}); 

but this will pick two random records among the first 20 , to be more accurate you need to count all records and then generate a random number between 1 and that count :

yourModel.count({}, function( err, count){

    var myRandom = Math.floor(Math.random() * (count - 1) + 1);

    // your old code ..
    .populate({
        path: 'path',
        options: {limit: 2, skip:myRandom}
    }); 
})

Upvotes: 1

Related Questions