如何使用NodeJS从MongoDB中读取BSON

时间:2018-08-06 23:40:01

标签: node.js mongodb bson

我想读取BSON二进制格式的数据,而不解析为JSON。这是下面的代码片段。 this.read()方法以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);
    });
});

控制台输出为“接收到的未定义数据字节”。这是因为块是对象,而不是BSON。

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

1 个答案:

答案 0 :(得分:2)

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

  

原始布尔值false可选以原始BSON缓冲区的形式返回文档结果

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