Introducing mongo-uri-builder, a Node.js module to easily create mongodb connection strings using objects

mongo-uri-builder simplifies creating MongoDB connection strings from configuration objects in Node.js

A couple of days ago I had the need to store the MongoDB connection string for a Node.js application I am currently building. Of course it was not a big deal and at first I stored it in a file. Anyway at some point I realised that I would needed to override parts of this string to change some settings in production (e.g. adding replicas and authentication settings). For this sake it would have been nice to have a way to store this configuration as a “well organised” object and then override just the properties I wanted to change.

I often use the config module to store my configuration and so I wanted to be able to do something like this in my configuration file:

  "mongo": {
    "host": "localhost",
    "port": 27017,
    "database": "mydb",
    "username": "loige",
    "password": "whyDoYouWantToKnowMyPassword"

And then to be able to retrieve this data and use it with a new MongoClient instance:

var MongoClient = require('mongodb').MongoClient
var config = require('config')

var mongoConfig = config.get('mongo')
  function(err, db) {

The missing bit here was the function createConnectionString. How to do that? I made a quick search on NPM and I wasn’t able to find something ready to be used… So, given that it was a quite easy task and that I enjoy to create new packages, I decided to build it by myself: welcome mongo-uri-builder! It’s alive!

Frankestain it's alive feeling when creating a new NPM library

(Yes, this was sort of the feeling I had after launching npm publish, call me crazy…)

The mongo-uri-builder package

mongo-uri-builder is a Node.js package to easily create mongodb connection strings using configuration objects.

The configuration object that the module expects looks like this:

var mongoConnectionConfig = {
  username: 'user', // the username
  password: 'pass', // the password
  host: 'host1', // the main host (default: "localhost")
  port: 1111, // the main port
  replicas: [
    // an array of replica databases
    // every replica must define an host, the port is optional
    { host: 'host2', port: 2222 },
    { host: 'host3', port: 3333 },
  database: 'db', // the name of the database
  options: {
    // an arbitrary object of connection options
    w: 0,
    readPreference: 'secondary',

All the properties are optional and you can even use an empty object. The classic mongodb://localhost will be generated as default in this case.

As we are used with NPM, installing the module is as easy as running:

npm install --save mongo-uri-builder

Then to use it you can do something like this:

var mongoUriBuilder = require('mongo-uri-builder')

var connectionString = mongoUriBuilder({
  username: 'user',
  password: 'pass',
  host: 'host1',
  port: 1111,
  replicas: [{ host: 'host2', port: 2222 }, { host: 'host3', port: 3333 }],
  database: 'db',
  options: {
    w: 0,
    readPreference: 'secondary',


// outputs "mongodb://user:pass@host1:1111,host2:2222,host3:3333/db?w=0&readPreference=secondary"

How easy and “well-readable” it is now? :)

Contributing & Issues

As I often do I put the code of the module on GitHub, you can find the repository at lmammino/mongo-uri-builder. Everyone is more than welcome to contribute to the project. You can contribute just by submitting bugs and pull requests or suggesting improvements by opening an issue.

Wrap up

This module is really something naive but it is a nice thing to have for me, especially in conjunction with config, that allows me to have different configuration files for every environment (e.g. development and production) and to override properties from a default configuration file. This way I can just override the parts of the connection string that are effectively different from the default configuration. I can even use environment variables if I don’t want for example to store the username and password of my database as clear text in a file.

I really look forward to knowing what you think about it and if you found it useful. Of course I also hope that you will be willing to give it a spin in your next Node.js project.

Ah, yeah, if you liked it don’t forget to share the love and “star” it on Github and Npm! ;)


Sharing is caring!

If you got value from this article, please consider sharing it with your friends and colleagues.

Found a typo or something that can be improved?

In the spirit of Open Source, you can contribute to this article by submitting a PR on GitHub.

You might also like

Cover picture for a blog post titled Unshorten (expand) short URLs with Node.js

Unshorten (expand) short URLs with Node.js

This article explains how short URLs work and provides code examples to expand them in Node.js using request module or tall library. It covers basics of URL redirection, shows how to disable auto-redirect in request module, and introduces tall - a promise-based Node.js library to unshorten URLs.

Calendar Icon

Cover picture for a blog post titled Introducing Gulp cozy - Manage your gulp tasks in a cozier way

Introducing Gulp cozy - Manage your gulp tasks in a cozier way

Gulp-cozy is an experimental NPM package that allows you to separate Gulp tasks into small modules inside a dedicated folder, making them easier to maintain. It brings Node.js modularity principles into your Gulp workflow.

Calendar Icon

Cover picture for a blog post titled Writing a new Extractor for PHPoAuthUserData

Writing a new Extractor for PHPoAuthUserData

This post explains how to add support for Instagram to the PHPoAuthUserData library by writing a dedicated extractor class. It illustrates the concepts of loaders, normalizers and mapping to extract user profile data from the Instagram API.

Calendar Icon

Cover picture for a blog post titled New PHP library: PHPoAuthUserData

New PHP library: PHPoAuthUserData

The PHPoAuthUserData library provides a simple interface to extract common user data like name, username, ID from various OAuth providers. It builds on top of PHPoAuthLib.

Calendar Icon

Cover picture for a blog post titled Migrating from Gatsby to Astro

Migrating from Gatsby to Astro

This article discuss the reason why I wanted to migrate this blog from Gatsby to Astro and the process I followed to do it. Plus a bunch of interesting and quirky bugs that I had to troubleshoot and fix along the way.

Calendar Icon

Cover picture for a blog post titled Middy 1.0.0 is here

Middy 1.0.0 is here

The middleware framework Middy reached version 1.0, bringing middleware capabilities to AWS Lambda. This allows cleaner handler code by extracting cross-cutting concerns into reusable middleware.

Calendar Icon