gpt4 book ai didi

node.js - MongoClient Node 游标流和数据管道

转载 作者:可可西里 更新时间:2023-11-01 09:59:04 28 4
gpt4 key购买 nike

我刚刚开始学习 Node 流,我正在使用 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)

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

最佳答案

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

从下面的代码片段来看:

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

关于node.js - MongoClient Node 游标流和数据管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30602729/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com