July 6, 2020
MongoDB with NodeJs CRUD Tutorial Guide

MongoDB with NodeJs CRUD Tutorial Guide

MongoDB with NodeJs has a huge demand in the market. Mongodb is a NoSQL based database that is it is unlike SQL, SQL server traditional relational database with rows and columns but rather store database in the form of collections than tables, Each collection consists of JSON documents. In this tutorial, we will set up the MongoDB database, set up node application, connect them using mongoclient, perform CRUD operations. So, if you have never worked with node, MongoDB still you will be able to follow up and get at par with everyone. So, let’s get started!

1.Set Up MongoDB Database

The first step of nodejs with MongoDB tutorial is to set up the database server. Go to the link and download the community edition https://www.mongodb.com/download-center/community

While installing choose mongoDB

Run service as Network User and then, compass Community 

MongoDB with NodeJs CRUD Tutorial Guide

To generate connection string, you need to create an account on https://cloud.mongodb.com/. Once, registered it will pick IP address, you have to give a username and password and it will generate connection string, similar to

mongodb+srv://<Username>:<Password>@cluster0-xxxxx.mongodb.net/test

Connect to compass GUI with connection string obtained as this connection string will also be used in node.js application

MongoDB with NodeJs CRUD Tutorial Guide

2.Node.Js Application Setup

As promised in this MongoDB with node.js tutorial, we will set up node.js application from scratch. So, nodejs is javascript based server engine where you write all the server-side code for your applications. To set up the application, first, make sure you have installed node.js and npm in your system,

then we need to create a folder, in that folder type npm init to initialize the repository as node.js application. you should see package.json file in the directory.

MongoDB with NodeJs CRUD Tutorial Guide

Create app.js file and type the following code

var msg=’Hello world!’;

console.log(msg)

Now, to run the application type node app.js

MongoDB with NodeJs CRUD Tutorial Guide

Now, you have successfully set up your node application. Now to connect to mongodb you need to install mongodb node.js driver that is mongoclient

On terminal, type

MongoDB with NodeJs CRUD Tutorial Guide

3. Create Collection in Database

Next step in mongodb with node.js tutorial is to create a database in mongodb, then create a collection under which we will Insert, Update, Delete records. Also, we will see how to first insert a data using the compass itself.

Here we have created engineerdiariesdb as database and users as collections

MongoDB with NodeJs CRUD Tutorial Guide

 

Insert 1 document into the collection

Under Add data insert document, add Json Object

MongoDB with NodeJs CRUD Tutorial Guide

MongoDB with NodeJs CRUD Tutorial Guide

4. Establish a connection with MongoDB

MongoDB with NodeJs CRUD Tutorial Guide

Replace your connection string, run using node app.js and if output on console is connected then you have successfully established connection with database MongoDB with nodejs.

const¬†MongoClient¬†=¬†require(‘mongodb’).MongoClient;
const¬†uri¬†=¬†“mongodb+srv://username:password@cluster0-xxxxx.mongodb.net/test”;
const client = new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology: true});
client.connect(err => {
¬†¬†const¬†collection¬†=¬†client.db(“EngineerDiariesDB”).collection(“Users”);
  // perform actions on the collection object
¬†¬†console.log(“connected”);
});

5. Insert a record in MongoDB with nodejs

const¬†MongoClient¬†=¬†require(‘mongodb’).MongoClient;
const¬†uri¬†=¬†“mongodb+srv://username:password@cluster0-xxxxx.mongodb.net/test”;
const client = new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology: true});
client.connect(err => {
¬†¬†const¬†collection¬†=¬†client.db(“EngineerDiariesDB”).collection(“Users”);
  // perform actions on the collection object
¬†¬†console.log(“connected”);
  var myobj = {
    id: 2,
¬†¬†¬†¬†name:¬†“Nidhi”,
    age:23
};  
collection.insertOne(myobj, function(err, res) {  
    if (err) console.log(err) ;  
¬†¬†¬†¬†console.log(“1¬†record¬†inserted”);¬†¬†
 
    });  
});

6. Update a record in MongoDB with nodejs

const¬†MongoClient¬†=¬†require(‘mongodb’).MongoClient;
const¬†uri¬†=¬†“mongodb+srv://username:password@cluster0-xxxxx.mongodb.net/test”;
const client = new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology: true});
client.connect(err => {
¬†¬†const¬†collection¬†=¬†client.db(“EngineerDiariesDB”).collection(“Users”);
  // perform actions on the collection object
¬†¬†console.log(“connected”);
collection.updateOne({
¬†¬†¬†¬†¬†¬†¬†¬†“name”:¬†“priyanka”
    }, {
        $set: {
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†“age”:¬†22
        }
    });
});

This will update record of name=priyanka, and set age to 22

7. Delete a record in MongoDB with nodejs

const¬†MongoClient¬†=¬†require(‘mongodb’).MongoClient;
const¬†uri¬†=¬†“mongodb+srv://username:password@cluster0-xxxxx.mongodb.net/test”;
const client = new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology: true});
client.connect(err => {
¬†¬†const¬†collection¬†=¬†client.db(“EngineerDiariesDB”).collection(“Users”);
  // perform actions on the collection object
¬†¬†console.log(“connected”);
 collection.deleteOne(
        {
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†“name”:¬†“priyanka”
        });
});

This will delete the record where name=priyanka

8. Record records in MongoDB with nodejs

const¬†MongoClient¬†=¬†require(‘mongodb’).MongoClient;
const¬†uri¬†=¬†“mongodb+srv://username:password@cluster0-xxxxx.mongodb.net/test”;
const client = new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology: true});
client.connect(err => {
¬†¬†const¬†collection¬†=¬†client.db(“EngineerDiariesDB”).collection(“Users”);
  // perform actions on the collection object
¬†¬†console.log(“connected”);
    collection.find({}).toArray(function(err, result) {
        if (err) console.log(err);
        console.log(result);
       // db.close();
      });
});

This will output all the documents in the collection.

 

So, this was short and complete tutorial on mongodb with node.js crud operations.

Similar Posts:
http://engineerdiaries.com/mean-stack-tutorial-in-30-minutes-2020/
http://engineerdiaries.com/express-js-routing-tutorial-beginners/
http://engineerdiaries.com/sql-server-with-nodejs-crud-operations/
http://engineerdiaries.com/mongodb-with-nodejs-crud-tutorial-guide/v

admin

Engineer Diaries started with the need to bridge the huge gap in what we are taught vs what the industry demands. We are based in Delhi, India but our blog is for everyone, in and outside tech industry‚̧ Feel free to reach out to us at engineerdiaries@gmail.com for any business/personal query.

View all posts by admin →

Leave a Reply