如何迭代 Model.stream waterline 查询的每条记录?

How to iterate on each record of a Model.stream waterline query?

我需要做类似的事情:

Lineup.stream({foo:"bar"}).exec(function(err,lineup){

  // Do something with each record
});

Lineup 是一个包含超过 18000 条记录的集合,所以我认为使用 find 不是一个好的选择。执行此操作的正确方法是什么?从文档中我不知道该怎么做。

.stream() method returns a node stream interface ( a read stream ) that emits events as data is read. Your options here are either to .pipe() to something else that can take "stream" input, such as the response object of the server, or to attach an event listener 从流发出的事件。即:

管道响应

Lineup.stream({foo:"bar"}).pipe(res);

设置事件侦听器

var stream = Lineup.stream({foo:"bar"});

stream.on("data",function(data) {
    stream.pause();        // stop emitting events for a moment
    /*
     * Do things
     */
    stream.resume();       // resume events
});

stream.on("err",function(err) {
    // handle any errors that will throw in reading here
});

.pause().resume() 非常重要,否则处理中的内容只会在代码完成之前继续响应发出的事件。虽然对于小案例来说很好,但对于更大的 "streams" 接口是不可取的。

此外,如果您像这样在事件处理程序中调用任何 "asynchronous" 操作,那么您需要在回调或承诺解析中注意 .resume(),从而等待 "async" 动作自行完成。

但请查看之前链接的 "node documentation" 以获得有关 "stream" 的更深入的信息。

P.S 我认为如果更适合您的感受,也应该支持以下语法:

 var stream = Lineup.find({foo:"bar"}).stream();