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 Node.js Node.js also provides a rich library of various Javascript modules which simplifies the development of web applications 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, and easy customization.

Step 1. Download Node.js from the link then install Node js.

Step 2. Download VS Code from this link and install it.

Step 3. Download MongoDB compass from the link to view the database and after downloading install MongoDB and run their service from the web service.

Step 4. Check the version of Node to run the 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 install the complete package(Library) from the service.

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 a 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 storing data in a database like SQL. Mongo DB has no requirements to declare the 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.

Connect your system to the internet open the command prompt and then run the 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 a 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) {
    if (error) {
        throw error;
    }
    var dbobject = databases.db('navigcollection');
    console.log("databases is created");
    databases.close();
});

Now compile this program in the terminal and write a command to compile

node createdb.js

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

CRUD Operation In MongoDB

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

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 the collection your database is shown in the databases list.

Step 10. Create a collection in the 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.

Create collection

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

Navigcollection

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

Pract

Step 11. Insert record in the 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");
    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 the terminal and write the command.

node insert1docu.js

The output will look like this.

Document inserted

Then open the database and refresh the collection.

Open database

Now insert a 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: "Dining 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("Number of documents inserted.........");
    });
});

Now compile this file in the terminal using the command.

node insertmanydocu.js

The output will look like this.

Output

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

Refresh the database

Step 12. Find records from the database

Find 1 record from the collection

Now create 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 found now....." + result.name + ", " + result.address + ", " + result.orderdata);
        databases.close();
    });
});

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

node findonedocu.js

The output will look like this.

Command

find many records from the 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);
        }

        databases.close();
    });
});

Now compile this program in the terminal and write a command for the compile.

node findmanydocu.js

After compilation, the output will look like this,

Compiler

Step 13. Update the record in the collection

Update one record from the 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 the terminal and write the command for compile.

node updateone.js

After compiling, this command output will show in the terminal like this.

Terminal output

The database will show like this without refreshing the database.

Without refresh database

After the refresh, the database output will look like this.

Database output

Now update records from the collection

To 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");
    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 the terminal using the command

node updatemany.js

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

Command output

Now go to the database

Before refreshing the database shows like this.

Before refresh database

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

Collection address value

Step 14. Now delete operation

deletes one record from the 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 the terminal and write a command for compile,

node deleteone.js

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

Document deleted

Now go to the database and check the database collection

Before refreshing the database output, it's shown like this.

Database collection

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

Database output collection

Now you can see there is no record with the name of Raju

Delete records from the 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 the terminal using the command.

node deletemany.js

After compiling this code output is shown in the terminal like this.

Deleted successfully

Now go to the database and check the database

Before refreshing the database, the database will be shown like this

Check database

After refresh database is shown like this.

Navigcollection pract

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.


Similar Articles