[英]MongoClient Node Cursor Stream and Piping of Data
I am just starting to learn about node streams, and I am using MongoClient ( MongoClient Cursor Doc ). 我刚刚开始学习节点流,并且正在使用MongoClient( MongoClient游标Doc )。 Within this document it states that I can get a returned query as a stream of documents. 在此文档中,它声明我可以将查询作为文档流来获取。 Like so: 像这样:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
var col = db.collection('streams');
// Insert a single document
col.insert([{a:1}, {a:1}, {a:1}], function(err, r) {
assert.equal(null, err);
assert.equal(3, r.result.n);
// Get the results using a find stream
var cursor = col.find({});
cursor.on('data', function(doc) {
console.dir(doc);
});
cursor.once('end', function() {
db.close();
});
});
});
Now I am trying to use the stream created by var cursor = col.find({});
现在,我尝试使用由var cursor = col.find({});
创建的流var cursor = col.find({});
to pipe into through2
and took out the listeners on data and end like so: 插入through2
并取出数据侦听器,并按以下方式结束:
var cursor = col.find({});
cursor.pipe(through2(function (buf, _, next) {
console.log('chunkString: ', buf.toString());
next();
}));
However, I get this error: 但是,我收到此错误:
/Users/blah/projects/mybuz/blah-ad/node_modules/mongodb/lib/utils.js:97
process.nextTick(function() { throw err; });
^
TypeError: Invalid non-string/buffer chunk
at validChunk (/Users/blah/projects/mybuz/blah-ad/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:164:14)
Dont know what I am doing incorrectly because I am piping from a readable stream to a duplex stream and just outputing that value on console. 不知道我做错了什么,因为我正在从可读流到双工流进行管道传输,而只是在控制台上输出该值。
I had a very similar problem. 我有一个非常类似的问题。 What turned out to have happened was that I was trying to pipe an object mode stream returned by MongoClient into a string/buffer stream. 原来发生的事情是我试图将MongoClient返回的对象模式流传输到字符串/缓冲区流中。 Which causes the error. 这会导致错误。
Judging by the snippet below: 从以下代码段判断:
var cursor = col.find({});
cursor.pipe(through2(function (buf, _, next) {
console.log('chunkString: ', buf.toString());
next();
}));
Your consuming stream is expecting a buffer. 您的消费流需要缓冲。
cursor.pipe(through2({ objectMode: true }, function(chunk, enc, next) {
console.log('chunk: ', chunk);
next();
}));
Should solve your problem. 应该解决你的问题。
source: https://nodesource.com/blog/understanding-object-streams 来源: https : //nodesource.com/blog/understanding-object-streams
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.