MongoClient节点游标stream和数据pipe道

我刚刚开始了解节点stream,我正在使用MongoClient( MongoClient光标文档 )。 在这个文档中,它声明我可以得到一个返回的查询作为一个文档stream。 像这样:

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(); }); }); }); 

现在我正在尝试使用由var cursor = col.find({});创build的streamvar cursor = col.find({}); 把数据通过pipe道through2取出来,然后像这样结束:

  var cursor = col.find({}); cursor.pipe(through2(function (buf, _, next) { console.log('chunkString: ', buf.toString()); next(); })); 

但是,我得到这个错误:

 /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) 

不知道我做错了什么,因为我从一个可读的streampipe道到一个双工stream,只是输出在控制台上的值。

我有一个非常类似的问题。 原来发生的事情是,我试图将一个由MongoClient返回的对象模式stream转换为string/缓冲stream。 导致错误的原因

从以下片段来判断:

 var cursor = col.find({}); cursor.pipe(through2(function (buf, _, next) { console.log('chunkString: ', buf.toString()); next(); })); 

你的消费stream正在期待一个缓冲区。

 cursor.pipe(through2({ objectMode: true }, function(chunk, enc, next) { console.log('chunk: ', chunk); next(); })); 

应该解决你的问题。

来源: https : //nodesource.com/blog/understanding-object-streams