Web Programming TutorialsLearn How to Integrate NodeJS into MongoDB Database

Learn How to Integrate NodeJS into MongoDB Database

NodeJS is a comparatively new programming environment than PHP and ASP. This technology has been adopted throughout the world for Web Development, Desktop Development as well as for Robotics. Though, many developers are aware ofNodeJS for Web Development and its asynchronous approach to deal with the requests.

NodeJS is new way to deal with the HTTP requests and many developers prefer to use a NoSql JSON database like MongoDB and CouchDB with it. NoSql database such as MongoDB has been built from scratch to be easily integrated with the web technologies such as HTTP and JSON. These databases are schemaless, which means you are not bound to create columns in your table. Your data is treated more like a document than a grid.

In Fact, there is no concept of tables in MongoDB. Basically what we have here is databases, collections and documents. All your JSON documents are arranged in a collection. Databases consist of multiple collections.

In this article, we’ll take you through NodeJS’s basic functionality with MongoDB. Make sure that you have the latest version of NodeJS and MongoDB installed on your device. You will also require NPM package manager to install the MongoDB driver. This is the MongoDB driver that we will use for this example. You can install this driver using the following NPM command from your terminal:

$ npm install mongodb --save

Make sure to execute this command from within your ‘codes’ folder that will further contain your NodeJS code file.


Once done, you are ready to write code. In your ‘codes’ directory, you need to create a .js file. You can name it anything you like and the very first thing that we will do in this file is to create a connection to your MongoDB server. Make sure that your MongoDB server is up and running.

   /* initializing */
    var mongo_client = require('mongodb').MongoClient

    /* making the connection and performing the functions */
    mongo_client.connect('mongodb://localhost:27017/', function(err, client){
   	 if(err == null) console.log("Successfully connected to the server.") // connection is successful
   	 else console.log(err) // connection failed

   	 /* if your database does not exist, then this command will create it */
   	 const db = client.db('marvel_world')

In the above code, we are first initializing the MongoDB wrapper. After that we are making a connection to our server. As NodeJS is asynchronous, all our functionality goes inside the callback function once the connection has been returned, i.e. ‘mongo_client.connect()’. We further setup the pointer to our database in the constant named ‘db’. Even if you ‘marvel_world’ database does not exist, this command will auto create it if not found without throwing any error.

Creating Documents

For the first task, we will create a bunch of documents in our newly created database. Please have a look at the code below:

   const collection = db_pointer.collection('heroes_profiles') // this collection will be auto generated if it does not already exist
    var records_to_be_created = []
    records_to_be_created.push({ // first record
    	"real_name": "Anthony Stark",
    	"alias": "Tony",
    	"weapons": [
        	"Shoulder mounted Guns",
    	"abilities": [
        	"Nuclear Powered Energy Core, known as 'Arc Reactor'",
        	"AI Armored Suit",
        	"Super Strength",
        	"Space Travel"
    	"love_interest": "Virginia 'Pepper' Potts"
    records_to_be_created.push({ // second record
    	"real_name": "Steve Rogers",
    	"alias": "Cap",
    	"weapons": [
        	"Vibranium Steel Alloy Shield",
        	"M1911A1 Handgun"
    	"abilities": [
        	"Super Human Strength",
        	"Super Human Agility",
        	"Super Human Speed",
        	"Super Human Endurance",
        	"Super Human Reaction",
        	"Bodily Functions to the peak of Human Efficiency"
    	"love_interest": "Peggy Carter"

    collection.insertMany(records_to_be_created, function(err, result){
   	 console.log('Inserted 2 documents into the collection.')
   	 db.close() // now close the connection

In the above code, we are using a library function named ‘insertMany()’ to insert more than one record at a time.

Here we are creating profiles of two superheroes, i.e. “Captain America” and “Ironman”.

Make sure you only run this code snippet once, executing more than once will create duplicate records.

Printing all documents

In the following code snippet, we fetch all the documents in our collection and print their contents on the screen.

  const collection = db_pointer.collection('heroes_profiles')
    collection.find({}).toArray(function(err, docs){
   	 console.log(docs) // print everything on the screen
   	 db.close() // now close the connection

In this code snippet, we use the wrapper function ‘find()’ to fetch the data, than convert it into an array and lastly print everything that we have got.

All your documents data would be printed in the JSON format.

Print single document

Printing all records is not very helpful, sometimes we just need a single record or records as per specific criteria.

We can specify this criteria in the ‘find() function’ in JSON format, an example is demonstrated below:

 const collection = db_pointer.collection('heroes_profiles')
    collection.find({'alias': 'Tony'}).toArray(function(err, docs){
   	 db.close() // now close the connection

The above code snippet searches all documents that contains ‘alias’ as ‘Tony’ in the ‘heroes_profiles’ collection and returns the found records.

Once found, we practically do the same as in previous example, thus print the results by first converting data to an array. Once done, we close the connection.

Updating specific document

In the following example, we lookup for the Captain America’s document and change the value of the property named ‘alias’ to a new one.

 const collection = db_pointer.collection('heroes_profiles')
    collection.find({'alias': 'Cap'}).toArray(function(err, docs){
   	 /* get Cap's record */
   	 var new_cap_record = docs[0]
   	 new_cap_record['alias'] = 'Nomad, The Captain'

   	 /* now change Cap's record */
   	 collection.updateOne({'alias': 'Cap'}, {$set: new_cap_record}, function(err, result){
   		 console.log("Updated Cap's document.")

Updating in MongoDB requires the complete document to be replaced. So, in this example we first locate Captain America’s record using the criteria defined in the ‘find() function’.

Once found, we create a new variable and initialize it with this fetched data. We now simply replace the original value contained in the ‘alias’ property with the desired value.

At last, we use the ‘updateOne() function’ and write down the complete document in place of the original one. In the next example, we will print Cap’s record on the screen.

Print Cap’s document

In order to print document data of Captain America’s document, we execute the following code snippet.

    const collection = db_pointer.collection('heroes_profiles')
    collection.find({'real_name': 'Steve Rogers'}).toArray(function(err, docs){
   	 db.close() // now close the connection

In the above code snippet, we look up for Captain America’s document using the property named ‘real_name’. Once found, we simply print it on the screen.

Removing/Deleting document

As the last example of this article, we will remove Ironman’s document. Please have a look at the code snippet below:

function delete_tony_record(db_pointer, callback){
    const collection = db_pointer.collection('heroes_profiles')
    collection.deleteOne({'alias': 'Tony'}, function(err, result){
   	 console.log("Removed Tony's document.")
   	 db.close() // now close the connection

All that we are doing in the above code snippet is using the ‘deleteOne() function’. We specify the filter criteria as the first argument and the second argument is our callback which gets executed once the found document is deleted.

Last words
These were the basic tasks that can be performed with this library. You can delve deeper and do much more with MongoDB and and NodeJS using this driver.

As a reference, corresponding code is also attached with this article.


Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -Newspaper WordPress Theme

Latest article


More article

- Advertisement -Newspaper WordPress Theme