如何使用 NodeJS 从 MongoDB 读取 BSON

How to read BSON from MongoDB with NodeJS

我想读取 BSON 二进制格式的数据而不解析为 JSON。这是下面的代码片段。 this.read() 方法 returns 数据采用 JSON 格式。我做错了什么?

const { MongoClient } = require('mongodb');
const config = {
    url: 'mongodb://localhost:27017',
    db: 'local',
    collection: 'startup_log'
}
MongoClient.connect(config.url, { useNewUrlParser: true }, (err, client) => {
    const db = client.db(config.db);
    const collection = db.collection(config.collection);
    const readable = collection.find({}, {fields: {'_id': 0, 'startTime': 1}});
    readable.on('readable', function() {
        let chunk;
        while (null !== (chunk = this.read())) {
          console.log(`Received ${chunk.length} bytes of data.`);
        }
        process.exit(0);
    });
});

控制台输出为 "Received undefined bytes of data"。这是因为 chunk 是一个对象,而不是 BSON。

我正在使用 "mongodb" 驱动程序 v3.1.1

http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html

raw boolean false optional Return document results as raw BSON buffers

const { MongoClient } = require('mongodb');
const config = {
    url: 'mongodb://localhost:27017',
    db: 'local',
    collection: 'startup_log'
}
const client = new MongoClient(config.url, {raw: true, useNewUrlParser: true});
//                                          ^^^^^^^^^^
client.connect((err, client) => {
    const db = client.db(config.db);
    const collection = db.collection(config.collection);
    const readable = collection.find({}, {
        fields: {'_id': 0, 'startTime': 1}
    });
    readable.on('readable', function() {
        const cursor = this;
        let chunk;
        while (null !== (chunk = cursor.read())) {
            const bson = new BSON().deserialize(chunk);
            console.log(`Received ${chunk.length} bytes of data.`, chunk);
        }
        process.exit(0);
    });
});