【问题标题】:MongoClient Node Cursor Stream and Piping of DataMongoClient 节点游标流和数据管道
【发布时间】:2015-08-16 15:18:46
【问题描述】:

我刚刚开始学习节点流,我正在使用 MongoClient (MongoClient Cursor Doc)。在本文档中,它声明我可以将返回的查询作为文档流获取。像这样:

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({}); 创建的流来管道到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)

不知道我做错了什么,因为我正在从可读流传输到双工流,并且只是在控制台上输出该值。

【问题讨论】:

  • 找到答案?
  • 否定,我放弃了,只使用常规回调,这在回调与流方面很糟糕。

标签: node.js mongodb stream


【解决方案1】:

我有一个非常相似的问题。结果发生的事情是我试图将 MongoClient 返回的对象模式流通过管道传输到字符串/缓冲区流中。这会导致错误。

通过下面的sn-p判断:

var cursor = col.find({});

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

您的消费流需要一个缓冲区。

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

应该可以解决你的问题。

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

【讨论】:

    猜你喜欢
    • 2013-07-11
    • 1970-01-01
    • 2017-03-29
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    相关资源
    最近更新 更多