Press "Enter" to skip to content

How to install Node.js with MongoDB on Ubuntu 16.04

install Nodejs MongoDB Ubuntu

Introduction

The two major stacks revolving around Javascript are MEAN (MongoDB, Express, Angular & Node) and MERN (MongoDB, Express, React & Node). Both the stacks are well suited for dynamic, extensive applications such as LinkedIn, Netflix, PayPal, etc.

Before we deep dive into connecting Node.js with MongoDB, let’s look at both of them in brief.

NodeJS is a Javascript runtime built on Chrome’s V8 Javascript engine. NodeJS uses a lightweight, non-blocking event-driven IO model which makes it efficient for asynchronous programming.

MongoDB is an open source, document-based database management system. Data in MongoDB is stored in JSON like documents that are schema-less. Thus MongoDB works great in scenarios where you can’t define a fixed data model.

Great! Let’s now look at how to connect Node.js with MongoDB on Ubuntu 16.04.

Initial Setup

Following components will be used.

  • Ubuntu 16.04 x64
  • MongoDB v3.2.16
  • Node.js v6.11.2 LTS
  • The MongoDB Node.js driver

*MongoDB is supported for all stable versions of NodeJS. For the purpose of this blog, we shall be using the above configuration.

Verify that NodeJS is installed on your system by typing the following command.

node -v

You should see the installed node version as an output.

V6.11.2

For a complete guide to NodeJS installation, you can visit here.

Verify that MongoDB process is running.

ps -ef | grep mongo

You should see an output like

mongodb  25400     1  0 10:57 ?        00:00:01 /usr/bin/mongod --quiet --config /etc/mongod.conf

If MongoDB is not running, execute the following command

sudo service mongod start

Alternatively, you can run the following command from MongoDB bin directory

mongod

MongoDB comes with an interactive javascript shell. You can use the mongo shell to query and update data as well as perform administrative operations.

Start the shell process by running the following command

mongo

You will see an output similar to this

MongoDB shell version: 3.2.16
connecting to: test

Let’s check the list of existing databases by typing

show dbs

This outputs list of existing dbs along with space occupied

local       0.078GB
security    0.078GB

In this post, we shall be using security. Issue the following command to use security

use security

Let’s see what’s inside this database

show collections

Output

system.indexes

Great, everything seems to be working fine, let’s move ahead with integrating mongodb and nodejs.

Connect with NodeJS

In order to connect Node.js with MongoDB, we need a MongoDB driver for NodeJS. Install the official MongoDB driver from npm using the following command inside your application directory.

npm install -P mongodb

After a successful installation, we are ready to connect our NodeJS application with MongoDB.

Let’s create a file call app.js that will contain the connection logic. In a file db_connect.js add the following code.

var MongoClient = require('mongodb').MongoClient;
var database = undefined;
var dbUrl = 'mongodb://127.0.0.1:27017/security';
MongoClient.connect(dbUrl, function(err, db) {
  if (err) {
    throw err;
  } else {
    database = db;
    console.log('MongoDB connection successful');
}
});

MongoClient object exposes a method connect, that returns a database object in callback. It has the following syntax.

connect(url, options, callback)

The first argument is a URL string with the following format

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

The second argument is an object literal that specifies optional settings like autoReconnect, poolSize, etc.

The third argument is a callback function that provides error on connection failure or database object in case of successful response.

Try executing this file by entering the following command from your application directory.

node db_connect.js

If the connection is successful, you will see console output as

MongoDB connection successful

Cool. So, we have successfully connected to the security database. Let’s try to insert some data in a new collection called users. Modify db_connect.js as below

var MongoClient = require('mongodb').MongoClient;
var database = undefined;
var dbUrl = 'mongodb://127.0.0.1:27017/security';
MongoClient.connect(dbUrl, function(err, db) {
  if (err) {
    throw err;
  } else {
    database = db;
    console.log('MongoDB connection successful');
    var testUser = {
      name: 'Suraj Poddar'
    };
    var users = db.collection('users');  
    users.insert(testUser, function(err, docs) {
      if (err) {
        throw err;
      } else {
        console.log(docs);
      }
    });
  }
});

A successful output will look something like this

MongoDB connection successful
{ result: { ok: 1, n: 1 },
  ops: [ { name: 'Suraj Poddar', _id: 59ad4719eb794f64c84e7ba6 } ],
  insertedCount: 1,
  insertedIds: [ 59ad4719eb794f64c84e7ba6 ] }

Awesome! We were successfully able to connect to a MongoDB server, read and write to it. For a complete list of APIs provided by MongoDB driver for NodeJS look for the `Releases` section here.

Here are a few more blogs on MongoDB which might interest you:  How to install MongoDB on Ubuntu and Top MongoDB ETL Challenges.

ETL Data to Redshift, Bigquery, Snowflake

Move Data from any Source to Warehouse in Real-time

Sign up today to get $500 Free Credits to try Hevo!
Start Free Trial

Related Posts

  • I’m walking here

    Let’s have a title called “How to install Node.js with MongoDB on Ubuntu 16.04” and, in the article, not really show how to install them.

    Even with the link to node installation, how about mongo? This could be “how to use”, maybe.

    In sum, don’t have an article about installing something and start by assuming it’s installed.