sollniss
sollniss

Reputation: 2003

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);
                });
            }
        });
    });
}

Upvotes: 0

Views: 297

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311945

Not sure if it's your only problem, but x will be a string, so if you want to compare it to arr.length you should either parse it into a number or just use == instead of ===.

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);
                });
            }
        });
    });
}

Upvotes: 1

Related Questions