KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

Node.JS Database MongoDB Tutorial

Introduction

MongoDB is a document based NoSQL database. It is one of the leading NoSQL databases. Node.JS has drivers that enable you to interact with MongoDB

In this tutorial, we will create a Node.JS database application that creates, reads, updates, and deletes documents from a MongoDB database. By the time that you are done with this tutorial, you would have created the following Node.JS console application

NodeJS MongoDB

Topics to be covered

We will cover the following topics in this tutorial;

  • Tutorial pre-requisites
  • Node.JS MongoDB Tutorial Database
  • Node.JS MongoDB Module
  • Node.JS MongoDB Create, Read, Update, and Delete (CRUD) Example

Tutorial pre-requisites

For you to successfully complete this tutorial, you will need to know the following.

  • You have already installed the latest version of Node.JS. If you havenít yet done so, then read the tutorial on how to install and configure Node.JS that guides you on how to download and install Node.JS
  • You have installed MongoDB server and its up and running
  • Command line / terminal Ė Node.JS makes heavy use of the command line
  • Active internet connection Ė we need to download packages from the internet
  • A text editor / IDE Ė you need it to write code
  • JavaScript basic skills Ė you donít need to be a JavaScript ninja to successfully complete this tutorial. Just the basics

Node.JS MongoDB Tutorial Database

We will create a simple database that records the information of music artists. This section assumes you already have downloaded and installed MongoDB. If you havenít you can download MongoDB from the following link.

https://www.mongodb.com/download-center

Download the appropriate set-up for your operating system. I am using windows operating system 64 bit.

Letís now start the server for MongoDB. We will need to run the command prompt as an administrator to avoid permission denied issues.

Search for the command prompt

Right click and select run as administrator as shown below

Command Prompt Run as Administrator

The title bar for the command prompt should show Administrator: Command Prompt

I installed MongoDB to the default path. I am assuming you did the same.

Run the following command

cd C:\Program Files\MongoDB\Server\3.2\bin

We will now set the Data path in the installation directory. You can choose any directory that you want.

Run the following command to create the Data directory

mkdir Data

Letís now set the database path and start the server.

mongod.exe --dbpath "C:\Program Files\MongoDB\Data"

HERE,

  • The above command sets the dbpath to the path "C:\Program Files\MongoDB\Data"

Letís now create our database and add some artist documents

Open another command prompt window

Run the following command

cd "C:\Program Files\MongoDB\Server\3.2\bin"

Run the command command

mongo.exe 

HERE,

  • The above command gives us an interactive terminal that we can use to play around with MongoDB server.

Use the following command to create the artistsí database

use ArtistsDB

Letís now add some documents to our database

Run the following command

db.artists.insert([
    {"name":"Disturbed",
        "genre":"Heavy Metal",
        "label":"Warner Bros.",
        "country":"United States"
    },

    {"name":"Behemoth",
        "genre":"Blackened Death Metal",
        "label":"Nuclear Blast",
        "country":"Poland"
    },

    {"name":"Diamond Platnumz",
        "genre":"Bongo Flava",
        "label":"Wasafi Records Blast",
        "country":"Tanzania"
    },

    {"name":"Slap Dee",
        "genre":"Zed Hip Hop",
        "label":"XYZ.",
        "country":"Zambia"
    }
])

Use the following command to retrieve all the documents that we just added

db.artists.find().pretty()

You will get the following results

Command Prompt Run as Administrator

Perfect, we can now write our node app that will interact with our database

Node.JS MongoDB Module

The mongodb module driver allows Node.JS applications to interact with MongoDB database. You can install the module using NPM. You can get more information about this module from the npmjs website https://www.npmjs.com/package/mongodb

Letís create a new project and install the module

I will create a new project mongo in drive C:\node\mongo. Feel free to use any directory or project name

Open the command prompt and browse to the project root directory.

npm init

Set the required parameters and say yes to create the package.json file

Letís now install mongodb module

Run the following command

npm install mongodb --save

HERE, - The above command installs mongodb module and adds it as a dependency to package.json file

Node.JS MongoDB Create, Read, Update, and Delete (CRUD) Example

Now that we have installed mongodb module and created a database, letís create a simple console app that will interact with our database.

Create a file app.js in the root directory

We will need to install console.table

Run the following command to install the console.table module

npm install console.table --save

Before we code our app, letís look at the methods that the app will have.

var mongodb = require('mongodb'); require('console.table');
var ObjectId = require('mongodb').ObjectId;

var MongoClient = mongodb.MongoClient;

var url = 'mongodb://localhost:27017/ArtistsDB';

var action = getArgument('--action');

function getArgument(argument){...}

function listRecords(db){...}

function addRecord(db){...}

function updateRecord(db){...}

function deleteRecord(db){...}

var action = getArgument('--action');

function rudAction(db){...}

MongoClient.connect(url, function (err, db) {...});

HERE,

  • var mongodb = require('mongodb'); require('console.table'); imports the mongodb and console.table modules
  • var ObjectId = require('mongodb').ObjectId; imports the ObjectId object. We will need it when finding documents using the _id field.
  • var MongoClient = mongodb.MongoClient; creates an instance of MongoClient
  • var url = 'mongodb://localhost:27017/ArtistsDB'; defines the URL that we will use to connect to the ArtistsDB
  • var action = getArgument('--action'); gets the argument values from the command line interface
  • function listRecords(db){...} retrieves all rows from the database and displays them in a beautiful table
  • function addRecord(db){...} inserts a new record into the database
  • function updateRecord(db){...} updates an existing record
  • function deleteRecord(db){...} deletes an existing record
  • function rudAction(db){ ...} used to decide the action i.e. add, update or delete record
  • MongoClient.connect(url, function (err, db) {...}); establishes a connection to the server, performs an action i.e. add, delete, or update and retrieves and displays the documents from the database.

The complete code for app.js is as follows

var mongodb = require('mongodb'); require('console.table');
var ObjectId = require('mongodb').ObjectId;

var MongoClient = mongodb.MongoClient;

var url = 'mongodb://localhost:27017/ArtistsDB';

var action = getArgument('--action');

function getArgument(argument){
    var index = process.argv.indexOf(argument);

    return (index === -1) ? null : process.argv[index + 1];
}

function listRecords(db){
    db.collection('artists').find().toArray(function(error,items){
        console.log();
        console.table(items);
        db.close();
    });
}

function addRecord(db){
    var name = getArgument('--name');
    var genre = getArgument('--genre');
    var label = getArgument('--label');
    var country = getArgument('--country');

    var artist = {name: name, genre: genre, label: label,country: country};

    db.collection('artists').insert([artist], function (err, result) {
        if (err) {
            console.log(err);
        } else {
            console.log();
            console.log('Created new artist with id ' + result.insertedIds);
        }
    });
}

function updateRecord(db){
    var _id = getArgument('--_id');
    var name = getArgument('--name');
    var genre = getArgument('--genre');
    var label = getArgument('--label');
    var country = getArgument('--country');

    var artist = {
        name: name,
        genre: genre,
        label: label,
        country: country,
    };

    db.collection('artists').updateOne({_id: ObjectId(_id)}, {$set: artist}, function (err, numUpdated) {
        if (err) {
            console.log(err);
        } else if (numUpdated) {
            console.log('Updated Successfully %d document(s).', numUpdated);
        } else {
            console.log('No document found with defined "find" criteria!');
        }
    });
}

function deleteRecord(db){
    var _id = getArgument('--_id');

    db.collection('artists').deleteOne({ _id: ObjectId(_id) }, function(err, result) {
        console.log("Removed the document with the id: " + _id);
    });
}

var action = getArgument('--action');

function rudAction(db){
    switch(action){
        case "add":
            addRecord(db);
            break;

        case "update":
            updateRecord(db);
            break;

        case "delete":
            deleteRecord(db);
            break;
    }
}

MongoClient.connect(url, function (err, db) {
    if (err) {
        console.log();
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {
        console.log();
        console.log('Connection successfully established to', url);

        rudAction(db);

        listRecords(db);
    }
});

Taking the app for a spin

Letís now take our app for a spin

Run the following command in the console. Make sure you are in the root directory

Displaying all records

node app

You will get the results

NodeJS MongoDB

Adding a new document

Before we add a new record, letís first examine the code behind the scenes

var name = getArgument('--name');
var genre = getArgument('--genre');
var label = getArgument('--label');
var country = getArgument('--country');

var artist = {name: name, genre: genre, label: label,country: country};

db.collection('artists').insert([artist], function (err, result) {
    if (err) {
        console.log(err);
    } else {
        console.log();
        console.log('Created new artist with id ' + result.insertedIds);
    }
});

HERE,

  • var artist = {name: name, genre: genre, label: label,country: country}; creates an array with the values submitted from the terminal.
  • db.collection('artists').insert([artist], function (err, result) {Ö}

inserts a new document into the artist collection

Go back to the console window and run the following command

node app --action add --name "Rick Ross" --genre "Hip Hop" --label "Self" --country "United States"

HERE,

  • node app runs our application
  • --action add tells the application what action to perform in addition to displaying the records
  • --name "Rick Ross" --genre "Hip Hop" --label "Self" --country "United States" specifies the values that should be inserted into the database

You will get the following results.

NodeJS MongoDB

The following command will update, delete existing records

node app --action update --_id "5778e1a0888aa6082a870e6d" --name "Raymond" --genre "Bongo Flava" --label "Wasafi" --country "Tanzania"

node app --action delete --id 5

Summary

In this tutorial, we have learnt how to connect to MySQL database using the mysql driver for Node.JS. We also looked at how we can create, read, update and delete data using prepared.

Whatís next?

The next tutorial will show you how to create a Node.JS REST API. The API will be powered by MySQL and you will be able to create, read, update and delete data. You will also learn how to use sequelize ORM.

If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didnít find it useful, please use the comments section below to let us know how we can do better next time.

Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when we publish new tutorials

Tutorial History

Tutorial version 1: Date Published 2016-08-02