How to find random record in Mongoose [duplicate]

The idea behind getting a random record is to query all the matching records but just get one. This is what findOne() does without any criteria given.

Then you will want to pick a random entry in all the possible matches. This is done by:

  1. Find out how many possible entries there could be – we use count() on the collection for this. Note that, as mentioned in comments, count is deprecated in version 4 and one should use estimatedDocumentCount or countDocuments instead. The different lies in precision/memory usage amongst other things. Here’s a SO post discussing it a bit.

  2. Come up with a random number within our count.

  3. Use skip() to “skip” to the desired match and return that.

Here’s a snippet as modified from this SO answer:

// Get the count of all users
User.count().exec(function (err, count) {

  // Get a random entry
  var random = Math.floor(Math.random() * count)

  // Again query all users but only fetch one offset by our random #
  User.findOne().skip(random).exec(
    function (err, result) {
      // Tada! random user
      console.log(result) 
    })
})

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)