Not sure how to use MongoDB with NodeJS? Don’t worry; this guide will help you.

Getting started with NodeJS

In the previous article, I covered in detail the steps to get you started with MongoDB. The articles cover in detail about the installation process as well as the terminologies that we use in MongoDB.

NodeJS is a popular Javascript-based backend technology that runs on Google Chrome’s Javascript V8 engine. NodeJS has become extremely popular as a backend language due to its reduced request overhead and freedom of coding in Javascript.

Being a JavaScript-based framework, it allows the front-end development experts to get started with the NodeJS backend easily.

This section covers a brief about setting up a NodeJS environment and writing your first NodeJS code.

The installation of NodeJS is pretty straightforward.

To install NodeJS, head over to the downloads page on the NodeJS site. Download the setup corresponding to your operating system. On executing the setup, it takes you through a guided easy-to-understand installation.

Ensure that you install the Node Package Manager (NPM) along with the installation of Node. Once the setup is completed, you could verify the installation by using the below command.

$ node -v
v8.11.1

Once you have installed node, let’s create a simple Javascript file and execute it with Node.

Create a file index.js in a directory of your choice and add the below code in it.

console.log('This is my first node application');
let a=5;
let b=10;
console.log('a+b='+(a+b));

Once you have saved the file, open the Terminal or command prompt. Navigate to the directory where the file is saved and execute the command as shown below.

$ node index.js

The node engine executes the code in the file and outputs the relevant statements in the terminal. The output of the above command will be as shown below.

This is my first node application
a+b=15

Installing NodeJS Plugin for MongoDB

Now that you have the database and the Node backend installed let’s proceed with the creation of a simple NodeJS project that can insert data into and retrieve data from the database.

In NodeJS, almost every task is made simple by the available plugins. Similar to the database drivers in Java, MongoDB plugin in NodeJS helps in communicating with the database with more straightforward commands.

The Node Package Manager(NPM) is a plugin used to install numerous NodeJS plugins with a single command.

To get started, create a practice directory and initialize it for a node project using the below commands.

Note: Although there are numerous IDEs available for NodeJS, I found Microsoft Visual Code to be the most user-friendly. Feel free to download it to make the process easier.

$ npm init
.
.
.

Press ^C at any time to quit.
package name: (node_practice)
version: (1.0.0)
description: Node JS to Mongo DB
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/abhishekkothari/Desktop/node_practice/package.json:

{
  "name": "node_practice",
  "version": "1.0.0",
  "description": "Node JS to Mongo DB ",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes)

Thus, the folder is initialized and now contains a package.json file.

This package.json file holds the details of the plugins that would be installed into the directory.

To install the MongoDB plugin for NodeJS, type in the below command.

$ npm install --save mongodb

This command installs the plugin in node_modules directory along with the necessary dependencies. The flag --save ensures that the plugin is added to the list of dependencies in package.json as shown below.

"dependencies": {
    "mongodb": "^3.0.10"
  }

Connecting and inserting the first document

Once the necessary plugin has been installed, it is time to insert our first document. Document in MongoDB is a single record inserted into one of the tables in the database.

To get started, start the MongoDB service using the below command.

$ ./mongod --dbpath=

In the case of Windows, use the below command.

> "C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe"

Starting with our first nodeJS code to connect to the database. Create an index.js file to start with. Add the below code in the file.

var mongo = require('mongodb')
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/newdb";

MongoClient.connect(url,
    function(err, db) {
  if (err) throw err;
  console.log("Database connected!");
  db.close();
});

Here newdb is the name of the database that you wish to put your data in. It is similar to a schema in MySQL.

However, the difference in case of MongoDB is that if you haven’t created a database, the plugin creates it for you. To insert the first document, update the index.js to reflect the below code.

var mongo = require('mongodb')
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/newdb";

MongoClient.connect(url,
    function(err, db) {
    if (err) throw err;
    console.log("Database connected!");
    var dbo = db.db("newdb");
    dbo.collection("students").insertOne({"name":"Abhishek","marks":100}, function(err, res) {
        if (err) throw err;
        console.log("1 document inserted");
        db.close();
    });
});

To save you the effort of re-executing the file each time, you could choose to install a plugin nodemon. Nodemon monitors for any file changes and automatically re-runs the file on change.

To install nodemon, use the npm command npm install -g nodemon.

The -g option installs nodemon globally. Thus, it would be available for use in every future node project.

Start nodemon using the simple command nodemon.

If all goes well, the first document would be inserted into the collection named students. As you might have noticed, you do not need to create the table first.

The table is automatically created when you insert the first document into it.

Inserting multiple documents

MongoDB functions on JSON strings. Hence, inserting multiple documents to MongoDB is quite simple. All you would need to do is to pass a JSON array to the right function to insert multiple documents.

Let’s update the code to insert multiple documents.

var mongo = require('mongodb')
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/newdb";
MongoClient.connect(url,
function(err, db) {
if (err) throwerr;
console.log("Database connected!");
vardbo=db.db("newdb");
dbo.collection("students").insertMany([{"name":"John","marks":90},{"name":"Tim","marks":80}], function(err, res) {
if (err) throwerr;
console.log("Documents inserted");
db.close();
});
});

As it can be noticed, there are two changes in the code. The function changes to insertMany and the first argument is now a JSON array. Thus, the documents passed as JSON array will be inserted into it.

View, filter and delete records

View records

Similar to insert function for inserting a document, the view records function also accepts JSON based filter.

To view all the records from the students table execute the below code.

var mongo = require('mongodb')
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/newdb";

MongoClient.connect(url,
    function(err, db) {
    if (err) throw err;
    console.log("Database connected!");
    var dbo = db.db("newdb");
    var results = dbo.collection("students").find({});
    results.forEach(row => {
        console.log(row);
    });
});

The function call find({}) takes in an empty JSON and hence returns all the documents available in the Database. The output for the above code will be similar to the one shown below.

Database connected!
{ _id: 5b1a1d323c5f4617b1263e49, name: 'Abhishek', marks: 100 }
{ _id: 5b1a20afb57cd517da966113, name: 'John', marks: 90 }
{ _id: 5b1a20afb57cd517da966114, name: 'Tim', marks: 80 }

Filter records

To filter the records, all you need to do is pass the filter attributes as a JSON in the find({}) function above. The code will look similar to the one shown below.

var mongo = require('mongodb')
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/newdb";

MongoClient.connect(url,
    function(err, db) {
    if (err) throw err;
    console.log("Database connected!");
    var dbo = db.db("newdb");
    var results = dbo.collection("students").find({marks:90});
    results.forEach(row => {
        console.log(row);
    });
});

Here, we filtered the records with marks equal to 90. The output for the above code will be similar to the one shown below.

Database connected!
{ _id: 5b1a20afb57cd517da966113, name: 'John', marks: 90 }

For more understanding about the filter strings, you could visit this link.

Delete records

Finally, it is time to delete the records. The delete operation in MongoDB using NodeJS is similar to finding a row.

The criteria are to be supplied using JSON that follows the filter string criteria pattern. A sample code to delete the record with marks = 90 is shown below.

var mongo = require('mongodb')
var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/newdb";

MongoClient.connect(url,
    function(err, db) {
    if (err) throw err;
    console.log("Database connected!");
    var dbo = db.db("newdb");
    dbo.collection("students").remove({marks:90});
    var results = dbo.collection("students").find({marks:90});
    if(!results.count==0){
        console.log('No record found');
    }
    results.forEach(row => {
        console.log(row);
    });
});

The above code deletes the records with marks = 90 and then checks whether the records exist or not.

The above code gives the output similar to the one shown below:

Database connected!
No record found

I hope this gives you an idea about using MongoDB with the Node.js application.

What’s next?

Become a professional programmer to level up your salary.