如何使用node-mongodb-native游标在Mongodb中进行分页?
问题描述:
我正在使用REST API,我需要能够通过MongoDB页面,从我所了解的光标是最好的方式来做到这一点。我可以获取游标,但是如何序列化它以将其发送到客户端?以及服务器在返回时如何反序列化并查询它?这甚至有可能吗?如何使用node-mongodb-native游标在Mongodb中进行分页?
collection.find({}, function(err, cursor) {
if (err) { console.log("Error in find: " + err); return;}
cursor.each(function(err, item) {
if (err) { throw err;
}
if (!item) {
console.log("All done");
} else {
console.log(sys.inspect(item));
}
});
});
问候,
答
您好我看见your question in the node-mongodb-native mailing list了。我知道你可以serializing query cursors in App Engine,但我不认为你可以在MongoDb中做精确的模拟。在Bigtable中,客户端获得的游标是被扫描的最后一行的实际密钥,而在MongoDb中,客户端的游标只有一个64位数字。根据MongoDb documentation on cursor timeouts来判断,因为每个未完成的游标占用数据库内存,所以不建议每个用户保留游标。
但是如果你仍然想使用MongoDb游标出于某种原因,我认为可以用cursor.js来破解,但我还没有尝试过自己。对于客户端来说,游标不过是一个64位的cursorId,你应该可以创建一个新的游标来发布正确的OP_GETMORE requests to the server。我认为它看起来像这样(未经测试!):
var cursorId = cursor.cursorId;
// ...
var cursor2 = new mongodb.Cursor(db, collection).limit(100);
cursor2.state = mongodb.Cursor.OPEN;
cursor2.cursorId = cursorId;
cursor2.toArray(function(err, results) {console.log(results);});