MEAN Stack User Registration -Back End In Node JS

In this article we’ll discuss MEAN stack user registration Or user sign up. Here we implement Node JS back end with MongoDB. In Part 2 we can add Angular 6 client side application to the same MEAN Stack Application.

GitHub link for this project :

MEAN Stack Tutorial Hierarchy

  1. CRUD Operation – Insert Update View and Delete.
  2. User Registration
    Node JS Back End.
    Angular 6 Front End.

Starting With Node JS Application

Following npm command will create package.json file to get started with Node JS Application.

It will ask for configuration details about the project (Just hit enter through them). Use following command to install npm packages – express, mongoose, body-parser, bcryptjs and cors.

application structure

Picture showing structure of project


Create MongoDB

In-order to work with MongoDB, we need to start MongoDB server. So let’s execute following lines in command prompt.

Open your MongoDB management tool – I use MongoDB Compass Community. Create a new Database.

Image Showing Creation MongoDB Database

Here we a created Database MeanStackDB with single collection users.

Create Mongoose Model For User Registration

Let’s create a mongoose model for user details. For that we need a model file user.model.js inside models folder.

Here we have created a mongoose schema for user containing

  • FullName
  • Email
  • Password
  • SaltSecret

Inside password field we will store encrypted password. Password encryption can be done using bcryptjs. Before encryption password will be merged with a random string ( salt secret ). Which is more secure than direct password encryption.

We have defined some validations like required validation, minlength validation and custom validation for email pattern. Also unique constraint for email address.

Finally we have called model function from mongoose to register the schema as User.

Add Node JS Configuration Details

To configure the application, we need a separate folder config. Inside the folder let’s add config.json file to store configuration details as follows.

PORT number for express server and MONGODB_URI for database details are mentioned separately for development and production environment. If needed you can add more configuration details to this same json file.

Now let’s create config.js file to configure the application with above details.

env variable stores current environment, By default it will be development. Manually you can pass environment through NODE_ENV  argument while starting your application as follows.

Configuration parameters are fetched into envConfig based on the environment. Inside the foreach loop, each of them is pushed into process.env key-value collection. Now it is easy to access PORT or MONGODB_URI from anywhere inside the application using process.env.

User Controller

Now we can save new user details inside MongoDB using mongoose model that we created above. For that we create user controller inside controllers folder.

Here we have exported register function, which can handle user registration request. Inside the function object of User schema is created and populated with user information from the request parameter. In-order to save the record we just need to call save function from schema object.

Inside the save function we have a callback function to be executed after save operation. If no error during the operation we will return doc parameter( which contains new record details including _id – which is automatically generated by MongoDB ). Inside the else clause we will implement error handling later.

Password Encryption

If you check the properties we used to save in MongDB, You can’t see the SaltSecret and yet we don’t have any password encryption so far. For this purpose we’ll use the pre-events from mongoose schema. That means generation of saltsecret and password encryptioncan be done inside pre-save event using bcryptjs. it will be triggered before the execution of save function in user controller. For that update user model file – user.model.js as follows.

genSalt function will generate a random string( SaltSecret ). using this saltsecret, hash function will encrypt the password. encrypted password and saltsecret is stored inside the schema object. Finally called the function next to continue the execution of mongoose save operation.

Create Route JavaScript File

Now it’s time to create the route javascript file – app.js ( you can name the file as you wish). all of the modules inside application are executed from route file.

First two require statement will invoke configuration( config.js ) and db setup( db.js ) JavaScript files. Then remaining package require statements are added.

bodyparser allows to receive JSON data from client side
cors package enables CORS- which is needed for making client side request from angular application.

Finally we have started the express server at port number ( that we specified inside config.json file –  process.env.PORT ).

Implement Routing

Let’s configure routing inside this application. In-order to handle common routes inside this application we will create index.router.js file in routes folder.

first we create router object using Router function from express package. Then a post route is set for register function from user controller using ‘/register’ URI. 

Exported router constant should be added to express midlleware in app.js as follows.

Try to follow order of lines inside this app.js file (from github link).

Now in-order to add a new user, we have to make a post request to ‘/api/register’ with new user details.

Error Handling

Final touch up! which is validation error handling. We handle duplicate email validation in user controller.

Violation of unique constraint can identified by code property in error object – 11000. if it occurs status code will be set 422 with custom validation error message.

Otherwise we continue the request by passing error object. Means error occurred due to other types of validations – required, minlength & email pattern. which we can be handled in app.js.

Types of error is identified by name property of error object. All of the validation errors are pushed in an array.  Which is returned as part of the response.

As a result of these error handling, if something went wrong in client application, we can have a properly formatted error message rather than messy error object from mongoose library.

Hope you found this helpful, Let me know if you need any help from my side. In the next part we will Implement Client Side Application for this MEAN Stack Project.

Step by Step Video Tutorial

Leave a Reply

Notify of