如何使用 MongoDB Node.js Driver Cursor 和 AggregateCursor 进行管道传输? [英] How to pipe with MongoDB Node.js Driver Cursor and AggregateCursor?
问题描述
不确定使用 MongoDB Node.js Drive 3.0.根据 docs,Cursor::pipe
和 AggregateCursor::pipe
接收可写流,因此您似乎应该能够执行以下操作:
Not sure of the proper way to pipe query results using MongoDB Node.js Drive 3.0. According to the docs, Cursor::pipe
and AggregateCursor::pipe
receive a Writeable streams so it seems like you should be able to do something like this:
collection.find(query).pipe(process.stdout);
collection.aggregate(query).pipe(process.stdout);
但结果是抛出错误:
TypeError: Invalid data, chunk must be a string or buffer, not object
这行得通,但对我来说感觉有点麻烦,不适合管道链接.
This works but it feels a little cumbersome to me doesn't lend itself to pipe chaining.
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 驱动程序创建标准管道链?
Is there a way to do a standard pipe chain with with the MongoDB Driver for Node.js?
推荐答案
看来错误是我试图将 objectMode
中的流通过管道传输到 objectMode<中的流的结果/代码>.这是一个解决方案:
It appears the error was the result of my trying to pipe a stream in objectMode
to a stream not in objectMode
. Here is a solution:
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);
您也可以扩展 stream.Writable
并将其设置为 objectMode
,但以上似乎是最简单的解决方案.
You could also extend stream.Writable
and set it to objectMode
, but the above seems like the simplest solution.
这篇关于如何使用 MongoDB Node.js Driver Cursor 和 AggregateCursor 进行管道传输?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!