使用Node&Redis获取10个随机项目
我试图找出如何从一个Mongo集合中获得一组10个随机项目。 我的计划是在Redis中存储一组Mongo ID,使用Redis SRANDMEMBER命令获取10个随机ID,然后从Mongo集合中获取它们。
由于我正在使用Node,所以我无法使用SRANDMEMBER 10,因为节点“redis”包不接受可选的第二个参数。
我真正绊倒的是如何以asynchronous友好的方式做到这一点。 我曾尝试使用由节点asynchronous库提供的几个工具,如Waterfall和While,但Redis调用总是比数据晚。
编辑#2:
为了回应下面的帮助,我已经完善了我的function:
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); }); });
使用redis
或node-redis
软件包的解决scheme是发送原始命令。
我已经testing了这两个软件包,都为我工作。
使用node-redis包
https://github.com/tim-smart/node-redis
node-redis
返回一个缓冲区对象数组。
client.sendCommand('SRANDMEMBER', ['album_id_set', '10'], function(err, reply) { for (var i = 0; i < reply.length; i++) { console.log(reply[i].toString()); }; });
使用redis包
https://github.com/mranney/node_redis
redis
返回一个string数组。
client.send_command('SRANDMEMBER', ['album_id_set', '10'], console.log);
有关更多信息,请参阅send_command文档。