0

I have tried finding a way of getting random records/documents in a MongoDB using mongoose without success.

The solution I found here failed which is four(4) years ago didn't solve my problem because it tends to skip some documents based on the generated random number.

The problem is that if you have 3 documents in the db and the random number generated is 3, doing the following as specified here:

User.findOne().skip(random).exec(
    function (err, result) {
      // Tada! random user
      console.log(result) 
    })

...will make .skip(3) to skip the whole three documents and return [] ( 404 error).

What I wanted was to shuffle record any time I do User.find()

Ezehlivinus
  • 83
  • 1
  • 9

1 Answers1

0

This is how I solved this problem

const users = await User.find().limit(50); // limit can be any number, each time you make a request, values will always be returned if have records is in your MongoDB

const randomUsers = users.sort(() => Math.random() - 0.5);

return res.status(200).send({ success: true, message: 'success: random users', data: randomUsers });

Any time you make a request, you are sure of getting a record but shuffled, reordered, or randomised the list based on the random number generated.

Trust this sovled a similar problem for you!

Ezehlivinus
  • 83
  • 1
  • 9