MongoDB with NodeJs CRUD Tutorial Guide

by Priyanka Arora
May 24, 2020
1272 Views
1
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!

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 

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


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.

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

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

npm install mongodb --save

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

Insert 1 document into the collection

Under Add data insert document, add Json Object


MongoDB with NodeJs CRUD Tutorial Guide

4. Establish a connection with MongoDB

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”);
});

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


Home

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.


Frequently Asked Questions

Mongodb is nosql based database and based on document structure providing more flexibility than sqlserver

Yes the query part remain exact same.

Yes. You can find that post in similar post below

Upload the file on server and store its link in the database

Similar Posts

Mean stack tutorial in 30 minutes-2020
May 24, 2020, 1272 Views, 1
Express Js Routing Tutorial | Beginners
May 24, 2020, 1272 Views, 1
Mysql with NodeJs Connection and CRUD
May 24, 2020, 1272 Views, 1
Sql Server with NodeJs CRUD Operations
May 24, 2020, 1272 Views, 1

Comments Section

Viraj
Nov 12, 2020

Nice post.