I'm trying to work out how to best get a set of 10 random items from a Mongo collection. My plan is to store a set of Mongo IDs in Redis, use the Redis SRANDMEMBER command to get 10 random IDs and then obtain them from the Mongo collection.
Since I'm using Node, I'm unable to use SRANDMEMBER 10, as the node "redis" package doesn't accept the optional second parameter.
Where I'm really stumbling though is how to do this in an async-friendly way. I have tried using several of the tools provided by the node async library, such as Waterfall and While, but the Redis call always comes in later than the data.
Edit #2:
In response to help below, I've refined my function down the following:
client.send_command("SRANDMEMBER", ["album_id_set", "10"], function(err, results) {
if (err) console.log('Redis error: ' + err);
Album.find({
'_id' : { $in: results }
}, function(err, result){
if (err) console.log('Mongo error: ' + err);
response.json(result);
});
});
The solution, using either the redis or node-redis package is to send the raw command.
I've tested both packages and both work for me.
https://github.com/tim-smart/node-redis
node-redis returns an array of buffer objects.
client.sendCommand('SRANDMEMBER', ['album_id_set', '10'], function(err, reply) {
for (var i = 0; i < reply.length; i++) {
console.log(reply[i].toString());
};
});
https://github.com/mranney/node_redis
redis returns an array of strings.
client.send_command('SRANDMEMBER', ['album_id_set', '10'], console.log);
See send_command documentation for more info.