简体   繁体   中英

How to find or get random records or documents in a mongodb using Mongoose

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()

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM