Warlock
Warlock

Reputation: 7471

How to read BSON from MongoDB with NodeJS

I want to read data in BSON binary format without parsing into JSON. Here is a code snippet below. this.read() method returns data in JSON format. What am I doing wrong?

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

Console output is "Received undefined bytes of data". This is because chunk is an object, but not BSON.

I'm using "mongodb" driver v3.1.1

Upvotes: 1

Views: 3307

Answers (1)

Warlock
Warlock

Reputation: 7471

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

Upvotes: 4

Related Questions