Node.js - CRUD Operations With Express And MongoDB - Day Thirteen

In previous articles, we learned about Express.js. Now, let's move to some advanced part of the Node.js. In this article, we will learn to perform the CRUD operations with Express.js and MongoDB. Today, we will work with MongoDB database. First of all, you should have MongoDB database installed in your system.

Introduction to MongoDB

MongoDB is a document-based open-source database. MongoDB is considered as a leading NoSQL database. It provides high performance, high availability, auto sharing and automatic scaling. MongoDB database is written mainly in C++. Its drivers and client libraries are typically written in their respective languages, although some drivers use C extensions for better performance. MongoDB differs from relational databases because it is a schema-less database. Such databases usually have lower transaction safety but are faster in accessing the data, and scale better than relational databases.

If you want to learn about installation of MongoDB, then you can read this article - MongoDB Installation.
 
You can get more information about MongoDB from here - MongoDB Articles.
 
After installing the MongoDB, let’s create a database, create a collection in that, and insert some data into that collection.

Run MongoDB Server

The “mongod” command is used to start a Server. This Server runs on Port Number 27017, by default.

MongoDB

Run MongoDB Client

The “mongo” command runs a MongoDb client that will connect to the Server running on specified Port 27017.

MongoDB

Create Database

The "Use" command switches you to the database if it already exists, otherwise it will create a new database. In our case, we don’t have database, so this command will create a new database.

MongoDB

Now, create an “EmpData” collection and insert some data into this.
  1. db.empData.insert({  
  2.     name: "Pankaj Choudhary",  
  3.     city: "Alwar",  
  4.     age: 22  
  5. })  
  6. db.empData.insert({  
  7.     name: "Sandeep jangid",  
  8.     city: "Jaipur",  
  9.     age: 23  
  10. })  
  11. db.empData.insert({  
  12.     name: "rahul Prajapat",  
  13.     city: "Delhi",  
  14.     age: 21  
  15. })  
MongoDB

Using “find” command, you can get data from collection and “find.pretty” command returns your data in a proper format.

MongoDB

Our MongoDB database is ready now. Let's create an Express project and use the aforementioned database into our project.

Open your Visual Studio and go to File-> New -> Project, click on “JavaScript” section, and select “Basic Node.js Express4 Application” project.

MongoDB

This project provides you a complete setup for Express project.

MongoDB

You can see this “npm” section contains some modules. But it doesn’t contain MongoDB module or we can say drivers. We need to install the MongoDB drivers manually. To install the MongoDB drivers, right click on project name and click on “Open command Prompt Here” option. It will open a command. Now, run the “npm install mongodb –save” command. This command installs all the required drivers for MongoDB.

MongoDB

Now, if you open the “npm”, you will find that MongoDb drivers have been installed in your project.

MongoDB
  1. var MongoClient = require('mongodb').MongoClient;  
  2. // Connection URL  
  3. var url = 'mongodb://localhost:27017/expressDB;  
  4.     // Use connect method to connect to the Server  
  5. MongoClient.connect(url, function(err, db) {  
  6.     console.log("Connected correctly to server");  
  7.     db.close();  
  8. });  
MongoDB

In the above lines of code, we created a mongoDB client and connected this to the Server that is running on “localhost” on port 27017. Before localhost, we defined “mongodb” that indicates that we are connecting to MongoDB database. In the last line, we connect the MongoDB client to the Server. After localhost, we defined the database name which is “expressDB”. Let’s try to run this program, using the command prompt.

Now, run the application. When you run the application, you will get the following output on the "Command Prompt" screen.

MongoDB

A window will open in the browser. If you get “Connected correctly to server” message, that means we are successfully connected to the MongoDB database.

MongoDB

After successfully connecting to the MongoDB setup, now, let's perform the CRUD operation.

Read Data from Collection
  1. var MongoClient = require('mongodb').MongoClient;  
  2. // Connection URL  
  3. var url = 'mongodb://localhost:27017/expressDB';  
  4. // Use connect method to connect to the Server  
  5. MongoClient.connect(url, function(err, db) {  
  6.             console.log("Connected correctly to server");  
  7.             console.log("Read Data rom empData Collection");  
  8.             //Create a Cursor uisng the find method  
  9.             var cursor = db.collection('empData').find();  
  10.             // Read data from curson  
  11.             cursor.each(function(err, data) {  
  12.                 console.log(data);  
  13.             });  
  14.             db.close();  
Output

MongoDB

In the above code, we fetch out the data from “empData” collection and store into “cursor” object. After that, we read the data from “cursor” object, using the each loop.

You can find more about Find method here - Find in MongoDB

Insert Data into Collection
  1. var MongoClient = require('mongodb').MongoClient;  
  2. var url = 'mongodb://localhost:27017/expressDB';  
  3. // Use connect method to connect to the Server  
  4. MongoClient.connect(url, function(err, db) {  
  5.     console.log("Connected correctly to server");  
  6.     //insert Data into Collection  
  7.     var sanjeev = {  
  8.         name: "Sanjeev Baldia",  
  9.         city: "Gurgaon",  
  10.         age: 24  
  11.     };  
  12.     var Narendar = {  
  13.         name: "Narendar Sharma",  
  14.         city: "Jaipur",  
  15.         age: 23  
  16.     };  
  17.     db.collection('empData').insert(sanjeev);  
  18.     db.collection('empData').insert(Narendar);  
  19.     console.log("Read Data rom empData Collection");  
  20.     //Create a Cursor uisng the find method  
  21.     var cursor = db.collection('empData').find();  
  22.     // Read data from curson  
  23.     cursor.each(function(err, data) {  
  24.         console.log(data);  
  25.     });  
  26.     db.close();  
  27. });  
Output

MongoDB

In the above code, we have created Sanjeev and Narendar objects. Using the insert method, we insert these data into empData collection. Then, we are using Find method to fetch out the new update data and show on the console screen.

You can find more about insert method here - Insert in MongoDB

Delete Data From Collection
  1. var MongoClient = require('mongodb').MongoClient;  
  2. // Connection URL  
  3. var url = 'mongodb://localhost:27017/expressDB';  
  4. // Use connect method to connect to the Server  
  5. MongoClient.connect(url, function(err, db) {  
  6.     console.log("Connected correctly to server");  
  7.     //delete Data ifromnto Collection  
  8.     db.collection('empData').remove({  
  9.         name: "Sanjeev Baldia"  
  10.     });  
  11.     console.log("Read Data from empData Collection");  
  12.     //Create a Cursor uisng the find method  
  13.     var cursor = db.collection('empData').find();  
  14.     // Read data from curson  
  15.     cursor.each(function(err, data) {  
  16.         console.log(data);  
  17.     });  
  18.     db.close();  
  19. });  
Output

MongoDB

In the above example, we used the delete method to remove the data from collection. There are other methods like remove and removeOne that you can use to delete the data.

You can find more about delete method here - Delete in MongoDB

Update Collection Data
  1. var MongoClient = require('mongodb').MongoClient;  
  2. // Connection URL  
  3. var url = 'mongodb://localhost:27017/expressDB';  
  4. // Use connect method to connect to the Server  
  5. MongoClient.connect(url, function(err, db) {  
  6.     console.log("Connected correctly to server");  
  7.     console.log("Read Data from empData Collection");  
  8.     //Create a Cursor uisng the find method  
  9.     var cursor = db.collection('empData').find();  
  10.     // Read data from curson  
  11.     cursor.each(function(err, data) {  
  12.         console.log(data);  
  13.     });  
  14.     //Update Data of empInfo Collection  
  15.     db.collection('empData').update({  
  16.         name: "Pankaj Choudhary"  
  17.     }, {  
  18.         $set: {  
  19.             age: 21  
  20.         }  
  21.     });  
  22.     console.log("Collection Updated Into data is below");  
  23.     //Create a Cursor uisng the find method  
  24.     var cursor = db.collection('empData').find();  
  25.     // Read data from curson  
  26.     cursor.each(function(err, data) {  
  27.         console.log(data);  
  28.     });  
  29.     db.close();  
  30. });  
Output

MongoDB

Update method takes two parameters - the selection criteria and the new data that will be updated for the selected data.

You can find more about update method here - Update in MongoDB

Conclusion

In this article, we learned some basic CRUD operations in ExpressJS using MongoDB database. Almost all commands of MongoDB run smoothly and similarly into ExpressJS. So, if you have knowledge of MongoDB database, then you can easily write queries in ExpressJS. Thus, I will recommended you to first learn MongoDB and then start working on ExpressJS.

You will find that the MongoDB is very easy to learn. I hope you liked this article.

Up Next
    Ebook Download
    View all
    Learn
    View all