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.
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.
Run MongoDB Client
The
“mongo” command runs a MongoDb client that will connect to the Server running on specified Port 27017.
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.
Now, create an “EmpData” collection and insert some data into this.
- db.empData.insert({
- name: "Pankaj Choudhary",
- city: "Alwar",
- age: 22
- })
- db.empData.insert({
- name: "Sandeep jangid",
- city: "Jaipur",
- age: 23
- })
- db.empData.insert({
- name: "rahul Prajapat",
- city: "Delhi",
- age: 21
- })
Using
“find” command, you can get data from collection and
“find.pretty” command returns your data in a proper format.
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.
This project provides you a complete setup for Express project.
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.
Now, if you open the “npm”, you will find that MongoDb drivers have been installed in your project.
- var MongoClient = require('mongodb').MongoClient;
-
- var url = 'mongodb:
-
- MongoClient.connect(url, function(err, db) {
- console.log("Connected correctly to server");
- db.close();
- });
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.
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.
After successfully connecting to the MongoDB setup, now, let's perform the CRUD operation.
Read Data from Collection
- var MongoClient = require('mongodb').MongoClient;
-
- var url = 'mongodb://localhost:27017/expressDB';
-
- MongoClient.connect(url, function(err, db) {
- console.log("Connected correctly to server");
- console.log("Read Data rom empData Collection");
-
- var cursor = db.collection('empData').find();
-
- cursor.each(function(err, data) {
- console.log(data);
- });
- db.close();
Output
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
- var MongoClient = require('mongodb').MongoClient;
- var url = 'mongodb://localhost:27017/expressDB';
-
- MongoClient.connect(url, function(err, db) {
- console.log("Connected correctly to server");
-
- var sanjeev = {
- name: "Sanjeev Baldia",
- city: "Gurgaon",
- age: 24
- };
- var Narendar = {
- name: "Narendar Sharma",
- city: "Jaipur",
- age: 23
- };
- db.collection('empData').insert(sanjeev);
- db.collection('empData').insert(Narendar);
- console.log("Read Data rom empData Collection");
-
- var cursor = db.collection('empData').find();
-
- cursor.each(function(err, data) {
- console.log(data);
- });
- db.close();
- });
Output
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
- var MongoClient = require('mongodb').MongoClient;
-
- var url = 'mongodb://localhost:27017/expressDB';
-
- MongoClient.connect(url, function(err, db) {
- console.log("Connected correctly to server");
-
- db.collection('empData').remove({
- name: "Sanjeev Baldia"
- });
- console.log("Read Data from empData Collection");
-
- var cursor = db.collection('empData').find();
-
- cursor.each(function(err, data) {
- console.log(data);
- });
- db.close();
- });
Output
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
- var MongoClient = require('mongodb').MongoClient;
-
- var url = 'mongodb://localhost:27017/expressDB';
-
- MongoClient.connect(url, function(err, db) {
- console.log("Connected correctly to server");
- console.log("Read Data from empData Collection");
-
- var cursor = db.collection('empData').find();
-
- cursor.each(function(err, data) {
- console.log(data);
- });
-
- db.collection('empData').update({
- name: "Pankaj Choudhary"
- }, {
- $set: {
- age: 21
- }
- });
- console.log("Collection Updated Into data is below");
-
- var cursor = db.collection('empData').find();
-
- cursor.each(function(err, data) {
- console.log(data);
- });
- db.close();
- });
Output
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.