Create an Authentication System with Node JS and MongoDB Part 1

5 months ago admin Nodejs

In this tutorial, we will create an Authentication System with Node JS and MongoDB, the user can register & log in with jwt token.


Install the packages

First, I assume that you have already a Mongodb account and you have created your database if not follow the link to see how to create the database.

Next, let's create the project folder you can name it as you want, inside add a new folder give it 'backend' as the name and inside run the commands:

                                                        
                                                                                                                        
npm init
npm install express mongoose cors nodemon bcryptjs jsonwebtoken

Connect to the database

Before we connect to the database update the file 'package.json' set the type to 'module' and add the script 'dev'.

Check the link for the demo. 

Next, create a new file 'config.js' inside the backend folder add the DB link inside, and change the user to your username and the password to your password.

                                                            
                                                                                                                                
export const db = "mongodb+srv://user:password@mern.hbwnmcq.mongodb.net/tasks?retryWrites=true&w=majority";

Create the userModel

Inside the backend folder create a new folder 'models' inside create a new file 'userModel.js' and add the code below inside.

                                                            
                                                                                                                                
import mongoose from "mongoose";

const userSchema = mongoose.Schema(
    {
        username: {
            type: String,
            required: true,
        },
        email: {
            type: String,
            unique: true,
            required: true,
        },
        password: {
            type: String,
            required: true,
        }
    },{
        timestamps: true
    }
);

const User = mongoose.model('User', userSchema);

export default User;