1

this is my first time asking a question on StackOverflow, and I apologize for it being more or less a repeat or if I've posted anything incorrectly. I'm trying to follow the code in Random record from MongoDB, but still struggling to retrieve 4 random records from my MongoDB in Node.

In the Mongo shell, I can successfully retrieve 4 random records with this:

db.reccs.find( { genre: { $in: ['fantasy']} } ).limit(4).skip(Math.random() *   db.reccs.count( { genre: { $in: req.query.test} } ))

However, in my Node.js server.js file, this code returns no errors and the first 4 records it finds, not a random 4:

  app.get('/comics', function(req, res) {
  var comics = db.collection('reccs').find( { genre: { $in: req.query.test} } ).limit(4).skip(Math.random() * db.collection('reccs').count( { genre: { $in: req.query.test} } )).toArray(function(error, comics) {
  if (error) {console.dir(error+"error!")}

  res.send(comics)
}) })

I'm totally stumped, so I'd appreciate any thoughts on why this works in the Mongo shell but not in server.js. Thank you!

edit - I believe this question is different because it is not about the Mongo shell, but Node.js - the solution in the linked question does absolutely work in the shell, just not in Node.js.

edit 2 - If anyone ever comes across this, this MongoDB count() undefined along with the comment below should help!

Community
  • 1
  • 1
Victoria
  • 21
  • 2

1 Answers1

1

Math.random() * some number will not give you integer ...

console.log(Math.random() * 22)
// 12.282829137984663

Therefore your skip (probably) never executes. Try

var numRecordsToSkip = Math.round(Math.random() * numRecords, 0)
.limit(4).skip(numRecordsToSkip) ...
jpaljasma
  • 1,612
  • 16
  • 21