Configuring a MongoDB Connection in Expressjs

Configuring a MongoDB connection in Expressjs requires a few lines of code which can easily be placed within your node application. If you haven’t recently set up an Expressjs project, you can learn how to do so here.

Firstly, download the mongodb package.

$ npm install mongodb

This will download the package into your project’s node_modules directory. You can include the MongoClient within your project by requiring the module. Usually this code is placed within the app.js file.

// app.js
var express = require('express');

....

// Define the MongoClient
var MongoClient = require('mongodb').MongoClient;

Using mLab

If you’re using a development environment, you can sign up to mLab and create a free sandbox deployment.

To do this, within your mLab account, click on the create new deployment link and choose the sandbox option.

Configuring a MongoDB Connection in Expressjs

You can then set a name of your database and save the deployment within your account.

Configuring a MongoDB Connection in Expressjs

Now that the database has been saved, you can click on it to add collections. Firstly, you should add a database username and password so that you’ll be able to configure the connection within the Expressjs application.

To do this, navigate to the ‘Users’ tab and click the ‘Add database user’ button.

Within your mLab account, you should be provided with a connection string that you can use to connect to your database. It might look something like this:

mongodb://<dbuser>:<dbpassword>@ds137540.mlab.com:37540/<dbname>

Where <dbuser> is the name of the database user set up in mLab, <dbpassword> the database user’s password, and <dbname> the name you gave your database. Replace these placeholders with your database information and you will be ready to add the connection string in your project.

Within the Expressjs application, you can add the connection string within app.js as a string parameter in the connect method of MongoClient.

MongoClient.connect('mongodb://<dbuser>:<dbpassword>@ds137540.mlab.com:37540/<dbname>', function (err, db) {
  if (!err) {
    console.log('MongoDB connected');
  } else {
    throw err
  }
});

If you start your Node application using the node app.js command, if you have configured your database connection you should see the ‘MongoDB connected’ line print out in your terminal.

Assuming you have used the Expressjs application generator, you should also see the ‘Express Server listening’ text when starting up the application.

$ node app.js
Express server listening
MongoDB connected