Registration/Login using the MongoDB to store data in expressJS

Onkar Shingate
Nerd For Tech
Published in
5 min readJun 10, 2021

******** Part 1:-Handling registration part. *******

Step 1:-

  • First, install express-generator and nodemon packages globally into your system.
npm i --global express-generatornpm i --global nodemon

Express-generator”:- this will help you setup basic server

nodemon”:- this will restart your server automatically after you save changes.

  • Now, we can set up a basic express server by just typing:-
express --view=ejs --css=sass <ProjName>
  • Now, for creating Models to store data in MongoDB we have to install the “mongoose ”package.
npm i mongoose --save

Step 2:-

  • Now, we have to create a User model to store data inside MongoDB. we have to create a new folder named “models” at the root. Once done, we have to create a new “User.js” file inside folder /root/models/ .
  • We can set up our model according to our needs refer to the image for more details.
creating the model for user data.

Step3:-

  • Now, we have to connect the MongoDB database to our server. so, first import mongoose into app.js file and before we initialize variable app write following code.
mongoose.connect('mongodb://localhost:27017/regis',{ useNewUrlParser: true, useUnifiedTopology: true },(err) => {console.log(err ? err : ' connection true');});
  • it will look like this:-
database connection

Step 4:-

  • now we have to add SignIn and Register links to our index page (root/views/index.ejs). which will help users to navigate to respective pages.
<a class="btn btn-pri" href="/users/login">Login</a><a class="btn btn-pri" href="/users/register">Register</a>
  • value of href attribute of login button has to be “/users/login” .
  • similarly, for register button href= “/users/register”.
adding links to the index page.

Step 5:-

  • Now, we have to handle routes of “/users” inside the users.js file which is inside folder “/root/routes”.
  • the Register button on the index page will do a GET request on /users/register route.
  • so to handle GET request on /users/register route we can send response as the userRegistrationForm.ejs file to the browser. this fill will contain a From inside it which has action= “/users/register” method= “POST”

tip:- all ejs files have to be into views folder ie(root/views/userRegistrationForm.ejs).

handling get request on route.
  • the userRegistrationForm.ejs file will look like this.
userRegisterForm.ejs file

Step 6:-

  • Once we fill the form and submit it, it will do a POST request on route “/users/register”.
  • now to add data into the database we need to import the User model. so into the users.js file inside routes folder. at the top, we have to require a User model.
let User = require('../models/User');
  • Now we can store form data inside “req.body” new variable data.
  • Now to add user into the database we can use User.create() method of mongoose.
  • once the user is created successfully we can redirect to “/users/login” route.
handling register request in the file “root/routes/users.js”

Step 7:-

**** encrypting(Hashing) password ****

  • until now we have stored password entered by the user as it is inside the database. this makes our passwords easily accessible by other peoples.
  • That's why we need to encrypt passwords while storing them in the database.
  • for Hashing (encrypting) password we need to install “bcrypt ”package into our server.
npm i bcrypt --save
  • now for encrypting password while registering new users we have to use mongoose middleware (hook) like pre(save).
  • every time User schema is called ,first it will executes pre hook and later do its work.
  • so to encrypt the password we have to use bcrypt.hash() method inside pre(save) hook.
  • in this hook, we have to change the password inside “req.body” to the hashed password.

tip:- we have to write pre(save) hook before we create model.

hashing password using bcrypt package.

********* Part 2: Handling login Part. *********

Step 1:-

  • The Login button on index.ejs page will do GET request on route “/users/login”.
  • to handle this GET request on “/users/login” route we have to just render “userLoginForm.ejs” page in response.
rendring userLoginForm.ejs file.

Step 2:-

  • “userLoginForm.ejs” file must contain a simple login form with fields email and password.
  • this form must have attribute ( action= “/users/login” method= “POST”)
  • the “userLoginForm.ejs” file will look like this.
“userLoginFrom.ejs” file

Step 3:-

  • Now to handle POST request on route “/users/login”, we have to first extract email and password from formData inside req.body.
  • on following 3 conditions server must be redirected back to “/users/login”.
  1. when email and password is empty.
  2. When email does not match with users in database.
  3. When password does not match with existing password in database.
  • Here we have to use User.findOne() method of mongoose to find user in database.
  • write respective cases mentioned above to handle errors.

Step 4:-

  • Remenber we have stored Hashed(encrypted) password into database but we have normal password now to match with hashed.
  • this problem can be solved using “bcrypt.compare()” method of the bcrypt package.
  • But first, we have to write the method inside the User model to check if passwords match. that we can do by defining method inside model by using
userSchema.methods.name=function(){};
adding checkpassword method.

Step 5:-

  • Now inside users.js file to handle routes we can use this checkPassword() method to check if the password matches or not.
  • Finally, the route handler must look like this:-
POST request on “/users/login”
  • This will return the “login Successful ” message as a response if the email and password match otherwise will redirect to the login page again.

--

--