不确定使用 MongoDB Node.js Drive 3.0 管道查询结果的正确方法。根据docs , Cursor::pipe
和 AggregateCursor::pipe
接收一个 Writeable 流,所以看起来你应该能够做这样的事情:
collection.find(query).pipe(process.stdout);
collection.aggregate(query).pipe(process.stdout);
但结果抛出一个错误:
TypeError: Invalid data, chunk must be a string or buffer, not object
这可行,但对我来说有点麻烦,不适合管道链接。
collection.find(query)
.on('data', function(chunk) {
buffer = Buffer.from(JSON.stringify(chunk))
process.stdout.write( buffer );
});
collection.aggregate(query)
.on('data', function(chunk) {
buffer = Buffer.from(JSON.stringify(chunk))
process.stdout.write( buffer );
});
有没有办法使用 Node.js 的 MongoDB 驱动程序创建标准管道链?
最佳答案
看来该错误是由于我尝试将 objectMode
中的流通过管道传输到非 objectMode
中的流造成的。这是一个解决方案:
collection.find(query)
.stream({
transform: function(chunk) {
return JSON.stringify(chunk);
}
}).pipe(process.stdout);
collection.aggregate(query)
.stream({
transform: function(chunk) {
return JSON.stringify(chunk);
}
}).pipe(process.stdout);
您还可以extend stream.Writable
并将其设置为 objectMode
,但上面似乎是最简单的解决方案。
关于node.js - 如何使用 MongoDB Node.js Driver Cursor 和 AggregateCursor 进行管道传输?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49806740/