【问题标题】:Merging streams in nodejs在nodejs中合并流
【发布时间】:2015-08-12 00:37:29
【问题描述】:

我正在使用 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) 变得更加棘手。

这个问题的解决方法是什么?

【问题讨论】:

    标签: node.js mongodb stream denormalization


    【解决方案1】:

    _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() 方法。

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 2020-12-31
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      相关资源
      最近更新 更多