CRUD Operation in MongoDB using Node.js, VS Code, MongoDB Compass

Introduction 

Node.js is an open-source, cross-platform and provides a run-time environment for developing server-side and networking applications. Node.js applications are written in JavaScript and can run within the Node.js Node.js also provide a rich library of various Javascript module which simplifies the development of web application using Node.js
 

VS Code

 
VS Code is a source-code editor developed by Microsoft for Windows, Linux, and iOS. The code supports many languages.VS Code intuitive keyboard shortcuts, easy customization.
 
Step 1
 
Download Node.js from the link and then install node js
 
Step 2
 
Download VS Code from this link and install
 
Step 3
 
Download MongoDB compass from link for view database and after download install mongodb and run their service from web service
 
Step 4
 
check version of Node to run command on cmd “ node -v”
 
Step 5
 
Open VS Code in your system and run a command to install npm “install npm -2 @angular/cli”
 
Then wait to done install the complete pakage(Liberary) from the servce
 
Step 6
 
After completing the installation, open VS Code in your system and select a folder to click on the Folder then open this folder in VS Code.
 

MongoDB 

 
Mongo DB is a cross-platform, open-source document-orient database. Mongod is NoSQL database(no structure). Mongo DB stores JSON data in the form of collections. MongoDB has no structure of the data, so it’s called NoSQL data. Mongo DB has no limit to store data into a database like SQL. Mongo DB has no requirements to declare length of the field like SQL/ Oracle / SqlYog.
 

CRUD Operation in MongoDB

 
CRUD stands for " create, read, update, and delete". Crud operations are used to create, read, update, and delete any documents.  
 
Step 1
 
Connect your system with the internet and open the command prompt and then run command 
  1. install mongodb --save  
This command is used to install the MongoDB package in your system. It will take more than 2 minutes. When it completes, then close the command prompt
 
Step 7
 
Create a database in MongoDB using Node.js and VS Code. first, open VS Code and create a folder where you want to make database program. and then open this folder in VS Code
 
Step 8
 
For performing any crud operation in MongoDB, you need a database and a collection. First. create a database and then create a collection.
 
Step 9 - Create a database
 
Create a .js page(createdatabase.js) and now write the code:
 
createdatabase.js 
  1. var mongodb=require('mongodb');  
  2. var MongoClient=mongodb.MongoClient;  
  3. var url='mongodb://localhost:27017/';  
  4. MongoClient.connect(url,function(error, databases){// use for to connect to the databases  
  5. if(error){  
  6.     throw error;  
  7.   
  8. }  
  9. var dbobject=databases.db('navigcollection');//use for create database   
  10. console.log("databases is created")  
  11. databases.close();  
  12.   
  13. })  
Now compile this program in terminal and write command for compile 
  1. node createdb.js  
After the compile, you should see that your database looks like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Now go to the mongodb compass and refresh the databases. after refreshing the database you see there is no database in databases.
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
 
Because an empty database doesn't show in the database list, to view the database we need to again create a collection in your database. After creating collection your database is shown in the databases list. 
 
Step 10 - Create collection in database
 
Create a .js file ("createcollection.js") and write code.
  
createcollection.js  
  1. var mongodb=require('mongodb');  
  2. var MongoClient=mongodb.MongoClient;  
  3. var url="mongodb://localhost:27017/"  
  4. MongoClient.connect(url,function(error,databases){  
  5.     if(error){  
  6.         throw error;  
  7.   
  8.     }  
  9.     var dbase=databases.db("navigcollection");  
  10.     dbase.createCollection("pract",function(error,response){  
  11.         if(error){  
  12.             throw error;  
  13.         }  
  14.       
  15.     console.log("collection is created.....")  
  16.     databases.close();  
  17.     });  
  18. });  
Now compile this program in the terminal and write the command for compile:
  1. node createcollection.js  
After compiling, the output will look like:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Now go to the database and refresh databases. After refreshing, the output will look like:
 
  CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Now click on your database and afterwards, click the collection shown:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Step 11 - Insert record in database  
 
Now insert a record in the collection, to insert a record in the database create a new page("insert1docu.js") and write code.
 
insert1docu.js"
  1. var mongodb = require('mongodb');  
  2.   
  3. var mongoClient = mongodb.MongoClient;  
  4. var url = "mongodb://localhost:27017/";  
  5.   
  6. mongoClient.connect(url, function(err, databases) {  
  7.       if (err)   
  8.       {  
  9.         throw err;  
  10.       }  
  11.       var nodetestDB = databases.db("navigcollection"); //here  
  12.       var customersCollection = nodetestDB.collection("pract");    
  13.       var customer = {_id:111, name:"Santosh Kumar" , address: "B-222, Sector-19, NOIDA", orderdata:"Arrow Shirt"};  
  14.         
  15.       customersCollection.insertOne(customer, function(error, response) {  
  16.           if (error) {  
  17.               throw error;  
  18.           }  
  19.         
  20.           console.log("1 document inserted");  
  21.           databases.close();  
  22.       });  
  23. });   
Now compile this program in terminal write command 
  1. node insert1docu.js  
Output will look like:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
 
Then open database and refresh collection:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Now insert record into the collection, create again a js file ("createmanydocu.js") and write the code:
 
createmanydocu.js
  1. var mongodb=require('mongodb');  
  2. var MongoClient=mongodb.MongoClient;  
  3. var url='mongodb://localhost:27017/';  
  4. MongoClient.connect(url,function(error,databases){  
  5.     if(error){  
  6.         throw error;  
  7.           
  8.     }  
  9.     var nodtst=databases.db("navigcollection");  
  10.   var pract=[  
  11.     {_id:11,name:"Chaman Gautam" , address: "Harvansh nagar Ghaziabad", orderdata:"Jeans"},  
  12.     {_id:12,name:"Shivani" , address: "Harvansh nagar Ghaziabad", orderdata:"Jeans"},  
  13.     {_id:13,name:"Menu" , address: "Harvansh nagar Ghaziabad", orderdata:"Top"},  
  14.     {_id:14,name:"Brajbala" , address: "Harvansh nagar Ghaziabad", orderdata:"Dinig table"},  
  15.     {_id:15,name:"Ramsaran" , address: "Harvansh nagar Ghaziabad", orderdata:"Washing machine"},  
  16.     {_id:16,name:"Dheeraj" , address: "Harvansh nagar Ghaziabad", orderdata:"Jeans"}  
  17.   ]  
  18. nodtst.collection('pract').insertMany(pract , function(error,response){  
  19.     if(error){  
  20.         throw error;  
  21.       
  22.     }  
  23.     console.log("Numnber of document is inserted.........");  
  24. })  
  25. })  
Now compile this file in the terminal using the command:
  1. node insertmanydocu.js  
Output will look like:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
 
Now go to the database and refresh the database, the database will look like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
Step 12 - Find  record from database
 
Find  1 record from collection
 
Now creata a .js page("find1docu.js")  create a page and write the code:
  1. var mongodb=require("mongodb");  
  2. var MongoClient=mongodb.MongoClient;  
  3. var url='mongodb://localhost:27017/';  
  4. MongoClient.connect(url, function(error, databases){  
  5.     if(error){  
  6.         throw error;  
  7.   
  8.     }  
  9.     var nodtst = databases.db("navigcollection");  
  10.     
  11.     nodtst.collection("pract").findOne({name:'Shivani'}, function(err, result) {  
  12.         if (err) throw err;  
  13.         console.log("one record is find now....."+result.name + ", " + result.address + ", " + result.orderdata);  
  14.         databases.close();   
  15.     })  
  16. })  
Now compile this program in terminal and write command for compile,
  1. node findonedocu.js  
Output will look like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
find many record from collection  
 
Now, create a new .js page("findmanudocu.js") and write the following code:
 
findmanudocu.js 
  1. var mongodb=require("mongodb");  
  2. var MongoClient=mongodb.MongoClient;  
  3. var url='mongodb://localhost:27017/';  
  4. MongoClient.connect(url, function(error, databases){  
  5.     if(error){  
  6.         throw error;  
  7.   
  8.     }  
  9.      
  10.     var nodtst = databases.db("navigcollection");  
  11.     nodtst.collection("pract").find({}).toArray(function(err, totalpract) {  
  12.         if (err) throw err;  
  13.           
  14.         for(i = 0; i < totalpract.length; i++) {  
  15.              let pract = totalpract[i];  
  16.            console.log(pract.name + ", " + pract.address + ", " + pract.orderdata);  
  17.          }  
  18.            
  19.            
  20.           
  21.         //console.log(result);  
  22.         databases.close();  
  23.     });    
  24. });  
Now compile this program in terminal and write command for the compile:
  1. node findmanydocu.js  
After compile, the output will look like,
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Step 13 - update record in collection
 
Update one record from collection 
 
Now you need to create 1 new .js file("updateone.js") and write the code:
 
updateone.js 
  1. var mongodb=require('mongodb');  
  2. var MongoClient=mongodb.MongoClient;  
  3. var url="mongodb://localhost:27017/"  
  4. MongoClient.connect(url,function(error,databases){  
  5.     if(error){  
  6.         throw error;  
  7.   
  8.     }  
  9.     var nodtst=databases.db("navigcollection");  
  10. var whereClause = { name:/Chaman Gautam/};  
  11. var newvalues = { $set: { name:"Lucky Gautam"}};  
  12. nodtst.collection("pract").updateOne(whereClause,newvalues,function(err,res){  
  13.     if(error){  
  14.         throw error;  
  15.   
  16.     }  
  17.     console.log(res.result.n + "document updated");  
  18. });  
  19. });  
Now compile this program in terminal and write the command for compile:
  1. node updateone.js  
After compiling, this command output will show in terminal like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
The database will show like this without refresh database:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
After refresh, the database output will look like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
 
Now update records from collection 
 
For update records in your database collection, you need to create a new .js file("updatemany.js") and write code 
 
updatemany.js
  1. var mongodb = require('mongodb');  
  2.   
  3. var mongoClient = mongodb.MongoClient;  
  4. var url = "mongodb://localhost:27017/";  
  5.     
  6.   
  7. mongoClient.connect(url, function(err, databases) {  
  8.   if (err)   
  9.   {  
  10.       throw err;  
  11.   }  
  12.   var nodeDB = databases.db("practicemongo"); //here  
  13.       var myquery = { address: /Harvansh nagar/ };  
  14.       var newvalues = {$set: {name: "Shivani"} };  
  15.       nodeDB.collection("pract").updateMany(myquery, newvalues, function(err, res) {  
  16.         if (err) throw err;  
  17.         console.log(res.result.nModified + " document(s) updated");  
  18.         databases.close();  
  19.       });  
  20.         
  21.         
  22.     });  
Now you need to compile this file in terminal using command 
  1. node updatemany.js  
After running this command output will be shown in the terminal like this
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Now go to the database 
 
Before refresh database show like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
After refresh, the database output will look like this now see the address in this collection address value will be changed
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
 
Step  14 - now delete operation
 
delete one record from collection
 
Now you need to create a new .js file("deleteone.js") and write code 
 
deleteone.js
  1. var mongodb=require('mongodb');  
  2. var MongoClient=mongodb.MongoClient;  
  3. var url ='mongodb://localhost:27017/';  
  4. MongoClient.connect(url,function(error,databases){  
  5.     if(error)  
  6. {  
  7.     throw error;  
  8. }  
  9.     var nodtst=databases.db('navigcollection');  
  10.     var deleteQuery={name:'Menu'};  
  11.    nodtst.collection("pract").deleteOne(deleteQuery,function(error,response){  
  12.         if(error){  
  13.             throw error;  
  14.   
  15.         }  
  16. console.log(response.result.n+" 1 document deleted......");  
  17. databases.close();  
  18.   
  19.     })  
  20.   
  21. });  
Now compile this program in terminal and write command for compile,
  1. node deleteone.js  
After compiling, the code output will be shown in the terminal like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
 
Now go the database and check the database collection 
 
Before refreshing the database output, it's shown like this
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
After a refresh, the  database output will be shown like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Now you can see there is no record with the name of Raju
 
Delete records from database  
 
Now you need again create a .js file ("deletemany.js") 
 
deletemany.js
  1. var mongodb=require('mongodb');  
  2. var MongoClient=mongodb.MongoClient;  
  3. var url='mongodb://localhost:27017/';  
  4. MongoClient.connect(url,function(error,databases){  
  5.     if(error)  
  6.     {  
  7.         throw error;  
  8.   
  9.     }  
  10.     var nodtst=databases.db('navigcollection');  
  11.     var deleteQuery={};  
  12.     nodtst.collection('pract').deleteMany(deleteQuery,function(error,response){  
  13.         if(error){  
  14.             throw error;  
  15.   
  16.         }  
  17.         console.log(response.result.n + "document(s) deleted successfully .....");  
  18.         databases.close();  
  19.   
  20.           
  21.   
  22.     })  
  23. })  
Now you need to compile this code in terminal using command 
  1. node deletemany.js  
After compiling this code output  is shown in terminal like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass 
 
Now go to the database and check database 
 
Before refresh database, the database will be shown like this
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
 
After refresh database is shown like this:
 
CRUD Operation In MongoDB Using Node.js, VS Code, MongoDB Compass
 
Now you will see that the database has a collection but no record in the collection
 
Now the CRUD operation in MongoDB using Node.js and VS code is complete.