Create an Authentication System with Node.js and MongoDB Part 1

Updated 2 weeks ago admin Javascript / Node.js

In this tutorial, we will create an Authentication System with Node JS and MongoDB.Ā The user can register & log in with a JWT token.

Install the packages

First, I assume that you already have 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;