CRUD (Create, Read, Update, Delete) using Node.js & MongoDB

Prerequisites : Node.js & MongoDB


Full Source Code available at : GitHub


Packages Used :


Express : Used to create server side application.
Mongoose : Used to connect MongoDB application.
bcryptjs : Used for encoding & decoding of data. We will use it for hashing.
morgan : Used to generate login. You can generate logs.
dotenv : Used to read value inside environment file.
body-parser : Suppose you are sending any data through POST using a variable then to read that data we use body-parser.
express-validator : To validate the data on different level.
cors : If your project has image linked from different website. Then this module creates secure environment for this data transfer.
nodemon : For auto restart of server on update of file.

Project Setup : Create a folder with any name and git bash in it. Now follow up the command to download different packages for the project.


Create package.json :

npm init

Other Packages :

npm install express mongoose bcryptjs express-validator body-parser cors morgan dotenv --save npm install -g nodemon

First thing first, create .env file inside your project directory. In this file the variable name is always in capital letters.

PORT = 3000
DB_URL = mongodb://127.0.0.1:27017/mongo_test

We will use DB_URL to establish connection to mongoDB using mongoose. You can get this by running your mongoose server. mongo_test is name of database which we will use in this project.



Now create index.js file and require all the installed packages.

require('dotenv').config();
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const app = express();
const port = process.env.PORT;

By including require('dotenv').config(); now we can use our .env file. process.env.PORT for our case listens to port 3000. And then we will setup our middleware.

app.use(morgan('dev'));
app.use(cors());

First we will create morgan with 'dev' (development) mode of log. Second is cors() module. Now we will create our default routes.

Now we will create our default routes.


app.all('/', function(req, res){
   return res.json({
      staus: true,
      message : 'Index page is working'
   });
});

All HTTP request whether from GET or POST will be handled here. In the above code we are returning json file to the user with status and message.

Now create file database.js. By this file we will establish connection with mongoDB.
// init code
const mongoose = require('mongoose');
const assert = require('assert');
const db_url = process.env.DB_URL;

// connection code
mongoose.connect(
   db_url,
   {
   	 useNewUrlParser : true,
   	 useUnifiedTopology : true,
   	 useCreateIndex : true
   },
   // link stores connection of database
   function(error, link){
      // check error
      assert.equal(error, null, 'DB Connect fail');

      // OK
      console.log("DB Connect Success");
      console.log(link);
   }
);


Now we will link this file with our index.js by typing :

const database = require('./database');

Now we will see brief overview of HTTP Methods :

GET        : For reading data
POST      : For creating new data entry / file in database
PUT        : Update existing data
DELETE : For deleting

You should also know basic HTTP status code

Now coming to mongoose related terminologies :

Schema : You can compare it as a Class in other programming languages. Like in class we create some functions same thing we do in schema. In this we create key for the database.
Model : To use our schema definition, we need to convert it into a Model we can work with.
Validators : It is sort of middleware which defines whether the data should be unique, required or of particular size

Creating Schema & Model

Create  models folder & then create user.js in it.
We will require mongoose package in this file & then create user schema.

const mongoose = require('mongoose');

Now we will create user schema in the file :

const userSchema = mongoose.Schema({
   username : {
      type : String,
      required : true
   },
   email : {
   	 type : String,
   	 required : true
   },
   password : {
   	 type : String,
   	 required : true
   },
   isActive : {
   	type : Boolean,
   	default : true
   },
   createdOn : {
   	 type : Date,
   	 default : Date.now()
   }
});

After this we will create user model :

mongoose.model('users', userSchema);

In this users is our collection name & userSchema is our schema which we created above. Then use will export this module through module exports.
 
Next create controllers folder & user.js (same as schema name in model) file in it. Basically for every model we create controller, in controller we define at which URL we perform which task on the model. In this file we will create initial code & middle ware & then we will export this using module.export so that we can include this file in our index.js
 
After the controller file has been setup successfully we will set initial code & middle ware in our index.js
 
Initial Code :
const userController = require('./controllers/user');

 

Middle ware :

app.use('/api/user', userController);

 

Now when you will visit http://localhost:3000/api/user/ you will notice below display which is coming from controllers folder:


Now we will see how we can use express validator to validitate & sanitize the HTTP requests coming to server side from form.


First we will create route 'createNew'  in controller. Then we will check whether the username is empty or not & then trim the username using .trim() (trim removes whitespaces present before & after the username). At last we will use .escape() (converts html special sysmbols into corresponding html code) 


check('username').not().isEmpty().trim().escape()

 

 

Then will follow same for password & email. For email we use isEmail() (built-in function that checks the validity of given email), normalizeEmail() (sanitize the email).

 

Then we will create function which check for error & in case of error return 422 status code & pass json file showing validitation  error. Else we will simply return json file showing no error foumd & user data.


After this using bcryptjs to hash our password.

const hashedPassword = bcrypt.hashSync(req.body.password, 10);

 

Now we will learn how to save our data in our database. For this we will use create() function & save username & password in database.

 

username : req.body.username

 

Since our password is hashed we will use the variable in which we have stored hashed password in our case its hashedPassword.

 

Now we will see how we can use create() function to store details in database.

User.create(
  {
    username : req.body.username,
    email : req.body.email,
    password : hashedPassword
  },
  function(error, result){
     // check error
     if (error) res.send("Error");
     else res.send("Successful");
  }
);

 

But we will not use this code instead we will use save() function to save data into database.

 

var temp = new User({
   username : req.body.username,
   email : req.body.email,
   password : hashedPassword
});

temp.save(function(error, result){
  if (error) res.send("Error");
  else res.send("Successful");
});

 

 Now to check working of this route open postman & go to URL localhost:3000/api/user/createNew

 

 

Now we will see how we can read data from our mongoDB database using /find route. For this we will use our 'User' model & find() method to find the data present in database. And then simply check for error else return the data. Now just run js file & your mongoDB server & from the browser go to :


http://localhost:3000/api/user/find

 

 Now we have covered Create & Read. Next is Update route in this put() method will be used. In this we have to update the username of email passed with the URL /update/:email. 

 First we will check whether the email is matching with the email present in our database by req.params.email If email matches then we will define what all things to update. In our case we are updating the username. And then simply check for error else return that everything is okay. Now since everything is done. Open your postman & pass email in the URL just as done below :

 Now in browser open http://localhost:3000/api/user/find you will find username updated to Shubham Arora.

 

Moving ahead to delete route. Just as update route we will pass email on our URL whose data we want to delete (localhost:3000/api/user/delete/milint@gmail.com)

Now on browser http://localhost:3000/api/user/find you will not find the record associated with this email.


Since we have completed all our CRUD task now we will see about login route & also how we can match our hashed password.


Important note : Throughout this tutorial we haven't used html form for sending data instead we have used postman to send data to server-side.

 

Moving ahead to login route; first we will validate our data using html validator

check('password').not().isEmpty().trim().escape(), check('email').isEmail().normalizeEmail()

 

Then we will check email exists or not in our database by this code : { email : req.body.email }. Finally we check check for error & check result matches or not. If result doesn't match we simply return error. Now using bcryptjs we check the password entered by user (req.body.password) with the password present in our database in hashed form (result.password). 

 

const isMatch = bcrypt.compareSync(req.body.password, result.password);

 

At last simply check password is matching or not using isMatch. Now simply go to postman at localhost:3000/api/user/login URL. Then just pass email & password you will get results accordingly.


Video ref. Sandeep Ganguli

No comments:

If you have any doubt or suggestion let me know in comment section.

Powered by Blogger.