dimanche 25 janvier 2015

Random selection of rows in MongoDB async

So I have read the other posts on how to get a selection of random rows but none work for me.


Random record from MongoDB and How to find random records in mongodb both suggest dated solutions that don't compile anymore.


Adding an extra random field to my database is not an option.


I've come up with the following code, but it also doesn't work.



exports.randomX = function(req, res)
{
var x = req.params.x;
db.collection('table', function(err, collection) {

collection.count(function(err, count) {
var r;
var arr = [];
for(var i=1; i<=x; i++)
{
r = Math.floor(Math.random() * count);
collection.find().limit(1).skip(r).toArray(function(err, items)
{
arr.push(items[0]);

if(arr.length === x)
res.send(arr);
});
}
});
});
}




Aucun commentaire:

Enregistrer un commentaire