Build a Login System in Node.js
By: Hussain Arif
Tags: Programming, JavaScript, Startup, Nodejs, Cybersecurity

Save Users to Database

The user schema and model

As usual, you have to define a schema before creating documents and saving them to the database. First, create the models directory and there create a file called user.js such that it is models/user.js . First, let’s create a schema in user.js . Next, we’ll create a model from that schema.

In models/user.js :

This means that your model will have a name, an email, its associated password, and the date of creation.

On line 20 , we’re using that schema in your User model. All of your users will have the data in this format.

Handling the POST request to the register directory: validation checks

In this step, you will create a document in the MongoDB database with the client-provided data.

At the beginning of the routes/users.js file, import the Mongoose library, and import the User model that you just created.

const User = require("../models/user.js")

Now, in the routes/users.js file, find the following piece of code:

Handling the register POST request

Within this handle, write the following code:

Line 1 : Extract the values from the elements in the form. You are taking out the email, the name of the user, his password. The last field ( password2 ) is a validation check to ensure that the user has confirmed that the password they are typing is correct.

: Extract the values from the elements in the form. You are taking out the email, the name of the user, his password. The last field ( ) is a validation check to ensure that the user has confirmed that the password they are typing is correct. Lines 4-6 : If any of the fields has not been filled, add an appropriate message to the error array.

: If any of the fields has not been filled, add an appropriate message to the array. Lines 8–10 : If the passwords don’t match, add the appropriate message to the error array.

: If the passwords don’t match, add the appropriate message to the array. Lines 13–15 : Check whether the password has a minimum of six characters.

: Check whether the password has a minimum of six characters. Lines 16–23 : If any content within the error array is present, re-render the register.ejs page and then send the appropriate data along with the errors array. All of the contents of this array will be displayed on the page.

: If any content within the array is present, re-render the page and then send the appropriate data along with the array. All of the contents of this array will be displayed on the page. Lines 24–36 : You have successfully passed the validation! Now you will first find if there is already a user present in the database via the email. If there is, then you will re-render the register.ejs page and display the relevant error. Otherwise, create a new user with the provided email, name, and its associated password. Bear in mind that you haven’t saved it yet. You will save it after encrypting the password.

As an example, let’s run the code and enter a single-character password so that it re-renders the page:

Output of the code after you deliberately enter the wrong options

You now need to display the errors, that is, display the contents of the errors array.

Display the errors

Now go to views/register.ejs and find the following piece of code (this will be around the beginning of the file):

Code to find at views/register.ejs

When you’ve found it, write the following line just under this h1 tag:

<%- include ('./partials/messages') %>

This line means import a new file that will help display the messages.

Go to your views directory, create a new directory called partials , and within partials , create a file called messages.ejs . There, write the following code.

views/partials/messages.ejs

<% if(typeof errors!= 'undefined') { %>

<% errors.forEach(function(error){ %>

<p> <%= error.msg %></p>

<% }) %>

<% } %>

This code says that if there are any errors present, then display the contents of the array with its own paragraph( p ) element.

Re-run the code and write a single character password. This will be the output:

Notice that you have now displayed the error message

If you leave any of the fields empty, then you will get this error message:

Two error messages displayed in this form

Make both password fields contain different values:

Three error messages displayed in this form

Handling POST requests to the register: save the users to the database

In this step, you will save the registered users to the MongoDB database. You will first encrypt their passwords and then save them to the database.

In routes/users.js , find the following piece of code:

Code in routes/users.js

Within this else block, write the following piece of code:

And on that note, end the else statement here.

Lines 2–7 : Generate a salt, hash the user’s password. Assign this encrypted value to the user’s password and then save the client to the database.

: Generate a salt, hash the user’s password. Assign this encrypted value to the user’s password and then save the client to the database. Line 10 : When the document is saved without errors, then redirect the user to the login directory, where the user will now log in with their credentials.

This will be the output of the code when you register yourself as a user:

Code output

Since you have logged out the contents of the document in your console, here’s the output in the console:

Contents of the newUser document

Enter a registered email. As expected, you get an error telling you that the email has already been stored:

Code output showing that you have an error

With this step, you’ve finally saved users to the database. Let’s move on to creating flash messages with Express.

At the end of this section, this is what your code looks like: