我正在使用MongoDB的游标流功能。在我的代码中,多个文档连接在一起,所以我想反规范化这些文档,然后将它们流式传输到客户端。我甚至不知道从哪里开始。下面是我尝试过的一些伪代码:
var stream = new Readable({ objectMode: true });
var cursor = collection.find();
cursor.forEach(fetch);
function fetch(document) {
stream.push(document);
// Get all joined documents and run fetch() on them
}
return stream;
我得到了一些错误,因为它没有实现_read
。这种方法还使得查找何时调用stream.push(null)
变得更加棘手。
这个问题的解决方案是什么?
发布于 2015-08-12 00:37:29
_read方法是实现可读流所必需的。如果您喜欢更简单的接口,您可能更喜欢使用PassThrough流:
var stream = new PassThrough({ objectMode: true });
var cursor = collection.find();
cursor.forEach(fetch);
function fetch(document) {
stream.write(document);
// Get all joined documents and run fetch() on them
}
return stream;
如果你想解决背压问题,使用一个可读的流是很有用的,但是我不确定mongodb API是否提供了这样的机制。
另外,看看mongodb API,看看如何正确地检查集合条目流结束,并相应地调用stream.end()方法。
https://stackoverflow.com/questions/31197133
复制相似问题