CRUD Operation in MongoDB with Node.js and VS Code

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

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

var mongodb=require('mongodb');  
var MongoClient=mongodb.MongoClient;  
var url='mongodb://localhost:27017/';  
MongoClient.connect(url,function(error, databases){// use for to connect to the databases  
if(error){  
    throw error;  
  
}  
var dbobject=databases.db('navigcollection');//use for create database   
console.log("databases is created")  
databases.close();  
  
})  

Now compile this program in terminal and write command for compile

node createdb.js  

After the compile, you should see that your database looks like this:

This is image title

Now go to the mongodb compass and refresh the databases. after refreshing the database you see there is no database in databases.

This is image title

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 - C****reate collection in database

Create a .js file (“createcollection.js”) and write code.

createcollection.js

var mongodb=require('mongodb');  
var MongoClient=mongodb.MongoClient;  
var url="mongodb://localhost:27017/"  
MongoClient.connect(url,function(error,databases){  
    if(error){  
        throw error;  
  
    }  
    var dbase=databases.db("navigcollection");  
    dbase.createCollection("pract",function(error,response){  
        if(error){  
            throw error;  
        }  
      
    console.log("collection is created.....")  
    databases.close();  
    });  
});  

Now compile this program in the terminal and write the command for compile:

node createcollection.js  

After compiling, the output will look like:

This is image title

Now go to the database and refresh databases. After refreshing, the output will look like:

This is image title

Now click on your database and afterwards, click the collection shown:

This is image title

**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"

var mongodb = require('mongodb');  
  
var mongoClient = mongodb.MongoClient;  
var url = "mongodb://localhost:27017/";  
  
mongoClient.connect(url, function(err, databases) {  
      if (err)   
      {  
        throw err;  
      }  
      var nodetestDB = databases.db("navigcollection"); //here  
      var customersCollection = nodetestDB.collection("pract");    
      var customer = {_id:111, name:"Santosh Kumar" , address: "B-222, Sector-19, NOIDA", orderdata:"Arrow Shirt"};  
        
      customersCollection.insertOne(customer, function(error, response) {  
          if (error) {  
              throw error;  
          }  
        
          console.log("1 document inserted");  
          databases.close();  
      });  
});   

Now compile this program in terminal write command

node insert1docu.js  

Output will look like:

This is image title

Then open database and refresh collection:

This is image title

Now insert record into the collection, create again a js file (“createmanydocu.js”) and write the code:

createmanydocu.js

var mongodb=require('mongodb');  
var MongoClient=mongodb.MongoClient;  
var url='mongodb://localhost:27017/';  
MongoClient.connect(url,function(error,databases){  
    if(error){  
        throw error;  
          
    }  
    var nodtst=databases.db("navigcollection");  
  var pract=[  
    {_id:11,name:"Chaman Gautam" , address: "Harvansh nagar Ghaziabad", orderdata:"Jeans"},  
    {_id:12,name:"Shivani" , address: "Harvansh nagar Ghaziabad", orderdata:"Jeans"},  
    {_id:13,name:"Menu" , address: "Harvansh nagar Ghaziabad", orderdata:"Top"},  
    {_id:14,name:"Brajbala" , address: "Harvansh nagar Ghaziabad", orderdata:"Dinig table"},  
    {_id:15,name:"Ramsaran" , address: "Harvansh nagar Ghaziabad", orderdata:"Washing machine"},  
    {_id:16,name:"Dheeraj" , address: "Harvansh nagar Ghaziabad", orderdata:"Jeans"}  
  ]  
nodtst.collection('pract').insertMany(pract , function(error,response){  
    if(error){  
        throw error;  
      
    }  
    console.log("Numnber of document is inserted.........");  
})  
})  

Now compile this file in the terminal using the command:

node insertmanydocu.js  

Output will look like:

This is image title

Now go to the database and refresh the database, the database will look like this:

This is image title

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:

var mongodb=require("mongodb");  
var MongoClient=mongodb.MongoClient;  
var url='mongodb://localhost:27017/';  
MongoClient.connect(url, function(error, databases){  
    if(error){  
        throw error;  
  
    }  
    var nodtst = databases.db("navigcollection");  
    
    nodtst.collection("pract").findOne({name:'Shivani'}, function(err, result) {  
        if (err) throw err;  
        console.log("one record is find now....."+result.name + ", " + result.address + ", " + result.orderdata);  
        databases.close();   
    })  
})  

Now compile this program in terminal and write command for compile,

node findonedocu.js  

Output will look like this:

This is image title

**find many record from collection **

Now, create a new .js page(“findmanudocu.js”) and write the following code:

findmanudocu.js

var mongodb=require("mongodb");  
var MongoClient=mongodb.MongoClient;  
var url='mongodb://localhost:27017/';  
MongoClient.connect(url, function(error, databases){  
    if(error){  
        throw error;  
  
    }  
     
    var nodtst = databases.db("navigcollection");  
    nodtst.collection("pract").find({}).toArray(function(err, totalpract) {  
        if (err) throw err;  
          
        for(i = 0; i < totalpract.length; i++) {  
             let pract = totalpract[i];  
           console.log(pract.name + ", " + pract.address + ", " + pract.orderdata);  
         }  
           
           
          
        //console.log(result);  
        databases.close();  
    });    
});  

Now compile this program in terminal and write command for the compile:

node findmanydocu.js  

After compile, the output will look like,

This is image title

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

var mongodb=require('mongodb');  
var MongoClient=mongodb.MongoClient;  
var url="mongodb://localhost:27017/"  
MongoClient.connect(url,function(error,databases){  
    if(error){  
        throw error;  
  
    }  
    var nodtst=databases.db("navigcollection");  
var whereClause = { name:/Chaman Gautam/};  
var newvalues = { $set: { name:"Lucky Gautam"}};  
nodtst.collection("pract").updateOne(whereClause,newvalues,function(err,res){  
    if(error){  
        throw error;  
  
    }  
    console.log(res.result.n + "document updated");  
});  
});  

Now compile this program in terminal and write the command for compile:

node updateone.js  

After compiling, this command output will show in terminal like this:

The database will show like this without refresh database:

This is image title

After refresh, the database output will look like this:

This is image title

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

var mongodb = require('mongodb');  
  
var mongoClient = mongodb.MongoClient;  
var url = "mongodb://localhost:27017/";  
    
  
mongoClient.connect(url, function(err, databases) {  
  if (err)   
  {  
      throw err;  
  }  
  var nodeDB = databases.db("practicemongo"); //here  
      var myquery = { address: /Harvansh nagar/ };  
      var newvalues = {$set: {name: "Shivani"} };  
      nodeDB.collection("pract").updateMany(myquery, newvalues, function(err, res) {  
        if (err) throw err;  
        console.log(res.result.nModified + " document(s) updated");  
        databases.close();  
      });  
        
        
    });  

Now you need to compile this file in terminal using command

node updatemany.js  

After running this command output will be shown in the terminal like this

This is image title

Now go to the database

Before refresh database show like this:

This is image title

After refresh, the database output will look like this now see the address in this collection address value will be changed

This is image title

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

var mongodb=require('mongodb');  
var MongoClient=mongodb.MongoClient;  
var url ='mongodb://localhost:27017/';  
MongoClient.connect(url,function(error,databases){  
    if(error)  
{  
    throw error;  
}  
    var nodtst=databases.db('navigcollection');  
    var deleteQuery={name:'Menu'};  
   nodtst.collection("pract").deleteOne(deleteQuery,function(error,response){  
        if(error){  
            throw error;  
  
        }  
console.log(response.result.n+" 1 document deleted......");  
databases.close();  
  
    })  
  
});  

Now compile this program in terminal and write command for compile,

node deleteone.js  

After compiling, the code output will be shown in the terminal like this:

This is image title

Now go the database and check the database collection

Before refreshing the database output, it’s shown like this

This is image title

After a refresh, the  database output will be shown like this:

This is image title

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

var mongodb=require('mongodb');  
var MongoClient=mongodb.MongoClient;  
var url='mongodb://localhost:27017/';  
MongoClient.connect(url,function(error,databases){  
    if(error)  
    {  
        throw error;  
  
    }  
    var nodtst=databases.db('navigcollection');  
    var deleteQuery={};  
    nodtst.collection('pract').deleteMany(deleteQuery,function(error,response){  
        if(error){  
            throw error;  
  
        }  
        console.log(response.result.n + "document(s) deleted successfully .....");  
        databases.close();  
  
          
  
    })  
})  

Now you need to compile this code in terminal using command

node deletemany.js  

After compiling this code output  is shown in terminal like this:

This is image title

Now go to the database and check database

Before refresh database, the database will be shown like this

This is image title

After refresh database is shown like this:

This is image title

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.

If you liked this post, share it with all of your programming buddies! Thank you!

#mongodb #node-js #javascript #vscode

CRUD Operation in MongoDB with Node.js and VS Code
47.05 GEEK