如何使用node-mongodb-native游标在Mongodb中进行分页?
我正在开发 REST API,我需要能够对 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));
}
});
});
问候,
I am working on a REST API, I need to be able to page through MongoDB, from what I understand cursor is the best way to do it. I can get the cursor, but how to serialize it to send it to the client? and how would the server de-serialize it when it comes back, and query with it? Is this even possible?
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));
}
});
});
Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您好,我在 您在 node-mongodb-native 邮件列表中看到的问题< /a> 也是。我知道您可以在 App Engine 中序列化查询游标但我认为你不能在 MongoDb 中进行精确的模拟。在Bigtable中,客户端获取的游标是扫描的最后一行的实际键,而在MongoDb中,客户端的游标只是一个64位数字。从 关于游标超时的 MongoDb 文档来看,它不是确实建议保留每个用户的游标,因为每个未完成的游标都会占用数据库内存。
但是如果您出于某种原因仍然想使用 MongoDb 游标,我认为可以使用 cursor.js 但我自己还没有尝试过。对于客户端来说,游标只不过是一个 64 位的游标 ID,您应该能够创建一个新的游标来发出正确的 OP_GETMORE 请求服务器。我认为它看起来像这样(未经测试!):
Hi I saw your question in the node-mongodb-native mailing list too. I know that you can serializing query cursors in App Engine but I don't think you can do the exact analogue in MongoDb. In Bigtable, the cursor that the client gets is the actual key of the last row that was scanned, whereas in MongoDb, the client's cursor is only a 64-bit number. Judging by the MongoDb documentation on cursor timeouts, it's not really advisable to keep around cursors per-user because each outstanding cursor takes up database memory.
But if you still want to use MongoDb cursors for some reason, I think it's possible to hack around with cursor.js but I haven't tried myself. To the client, a cursor is nothing more than a 64-bit cursorId, and you should be able to create a new Cursor to issue the correct OP_GETMORE requests to the server. I think it would look something like this (untested!):