Javascript, MongoDB, and Compose

Quick note: In this example, we are assuming that your Compose connection string is set in an environment variable MONGODB_URL, like this:

var MONGODB_URL="mongodb://user:[email protected]:port/db_name?ssl=true"

The code here uses the node-mongodb-native driver, version 3.0. Like all good Node packages, you can get it via NPM.

npm install mongodb

Connecting with Node.js

In this example, we are using pre ES6 JavaScript to connect to the server.

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var fs = require('fs');

var options = {
    ssl: true,
    sslValidate: true,
    useNewUrlParser: true
};


if (process.env.hasOwnProperty("MONGODB_CERT_PATH")) {
    var ca = [fs.readFileSync(process.env.MONGODB_CERT_PATH)];
    options.sslCA = ca;
}

MongoClient.connect(process.env.MONGODB_URL, options, function (err, client) {
    assert.equal(null, err);
    client.db().listCollections({}).toArray(function (err, collections) {
        assert.equal(null, err);
        collections.forEach(function (collection) {
            console.log(collection.name);
        });
        client.close();
        process.exit(0);
    })
});

Some Compose MongoDB deployments use self-signed certificates, such as Compose Enterprise MongoDB. With the certificate saved locally on disk, this example uses the MONGODB_CERT_PATH environment variable to pass the path to the certificate to the application. If it is not set, the example automatically assumes that the connection string is using a Let's Encrypt certificate.

If you prefer a more modern JavaScript (ES6 and later) flavor to your examples try:

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var fs = require('fs');

var options = {
    ssl: true,
    sslValidate: true,
    useNewUrlParser: true
};


if (process.env.hasOwnProperty("MONGODB_CERT_PATH")) {
    var ca = [fs.readFileSync(process.env.MONGODB_CERT_PATH)];
    options.sslCA = ca;
}

var dbclient;

MongoClient.connect(process.env.MONGODB_URL, options)
    .then(client => {
        dbclient = client;
        return dbclient.db().listCollections({}).toArray();
    })
    .then(collections => {
        collections.forEach(collection => console.log(collection.name))
    })
    .then(() => {
        dbclient.close();
        process.exit(0)
    })
    .catch(err => {
        console.log(err);
    })

Connecting with Mongoose and Node

The basic technique is the same as the Node.js/direct examples above. Create an options map, add in the requires SSL parameters and then pass that options map with the URL for MongoDB to the mongoose.connect() method. In the example below, as in the examples above, we can connect without a self signed certificate using Lets Encrypt certification, or with a self signed certificate.

const mongoose = require('mongoose');
var assert = require('assert');
var fs = require('fs');

var options = {
    ssl: true,
    sslValidate: true,
    useNewUrlParser: true
};


if (process.env.hasOwnProperty("MONGODB_CERT_PATH")) {
    var ca = [fs.readFileSync(process.env.MONGODB_CERT_PATH)];
    options.sslCA = ca;
}

mongoose.connection.on('error', console.error.bind(console, 'connection error:'));

mongoose.connection.on('open', (err) => {
    assert.equal(null, err);
    mongoose.connection.db.listCollections().toArray(function (err, collections) {
        assert.equal(null, err);
        collections.forEach(function (collection) {
            console.log(collection.name);
        });
        mongoose.connection.close();
        process.exit(0);
    })
});

mongoose.connect(process.env.MONGODB_URL, options);

Still Need Help?

If this article didn't solve things, summon a human and get some help!