Skip to main content

Command Palette

Search for a command to run...

User Registration in Node.JS | Express.JS | MongoDB

Published
4 min read
User Registration in Node.JS | Express.JS | MongoDB

Hi developers, In this blog we are going to develop user registration using Node js, before we jump into in, i am assuming that you are already familiar with Node js, express js, MongoDB... if yes then lets get started...

First of all create a node js project using npm init --yes and install these packages npm i express nodemon mongoose dotenv after installing these packages open the folder into any IDE and for running the project on CTRL+S go to package.json and add

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js" //add this line to run on CTRL+S
  },

Folder Structure

app.js
src/
├── config/
│   └── databaseConnect.js
├── controllers/
│   └── auth/
│       └── register.js
├── models/
│   └── user.js
├── Routes/
│   └── AuthRoutes.js
└── services/
    └── AuthService/
        └── register.js
.env

App.js

//external modules
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
require("dotenv").config();
//internal modules
const DatabaseConnect = require("./src/config/databaseConnect");
const authRoute = require("./src/Routes/AuthRoutes");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//connecting with the DB
DatabaseConnect();
//Routes
app.use("/user", authRoute);
//Initiate the server
app.listen(process.env.PORT, () => {
  console.log(`App is listening on port ${process.env.PORT}`);
});

databaseConnect.js

const mongoose = require("mongoose");
require("dotenv").config();

const DatabaseConnect = async (req, res) => {
  mongoose
    .connect(process.env.MONGO_URI) //store this into .env 
    .then(() => console.log("Database connected successfully!"))
    .catch((err) =>
      console.error(err, "Error occured while connecting to Database")
    );
};
module.exports = DatabaseConnect;

user.js (models)

In models we have to define the fields we want to store into database on user registration like in the below code we are taking firstName, lastName, email, password.

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema(
  {
    firstName: {
      type: String,
      required: true,
    },
    lastName: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      unique: true,
      trim: true,
      lowerCase: true,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

const userModel = mongoose.model("userModel", UserSchema);
module.exports = userModel;

regsiter.js (Controllers)

Controller is basically accept the request and return some response to the API request so first of all we collect the firstName, lastName, email, password from body and storing them into userData. Then calling the registerUser service with parameter userData.

const { registerUser } = require("../../services/AuthService/register");

const register = async (req, res) => {
  try {
    const userData = {
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      email: req.body.email,
      password: req.body.password,
    };

    //call the register service
    const result = await registerUser(userData);

    if (result.success) {
      res.status(201).json({ message: result.message, userId: result.userId });
    } else {
      res.status(400).json({ message: result.message });
    }
  } catch (err) {
    res
      .status(500)
      .json({ message: "Internal server error", error: err.message });
  }
};
module.exports = register;

regsiter.js (Services)

This is where we write our main logic (business logic) in service module we play with database and perform operations. In our current scenario we are destructuring the userData then checking for is user already exist with the help of email. If user already exist then we throw an error. If not then we moved to next step that is hashing the password before storing into database, so for that we using bcrypt.

After all checks and operations we store the user into database.

const User = require("../../models/user");
const bcrypt = require("bcrypt");
const saltRound = 10;

module.exports.registerUser = async (userData) => {
  try {
    const { firstName, lastName, email, password } = userData;

    //checking for email existance
    const existingUser = await User.findOne({ email });
    if (existingUser) {
      throw new Error("User is already exist!");
    }

    //Hash the password
    const hashedPassword = await bcrypt.hash(password, saltRound);

    //create a new user instance
    const newUser = new User({
      firstName,
      lastName,
      email,
      password: hashedPassword,
    });

    await newUser.save();
    return {
      success: true,
      message: "User registred successfully!",
      userId: newUser._id,
    };
  } catch (err) {
    return { success: false, message: err.message };
  }
};

AuthRoutes.js

For routing we use express.js in our current scenario our API endpoint will be :
http://localhost:8000/user/register

const express = require("express");
const router = express.Router();
const registerController = require("../controllers/Auth/register.js");

router.post("/register", registerController);
module.exports = router;

Testing

To test the API you have to open postman and enter url http://localhost:8000/user/register , request type POST JSON data would be :

{
  "firstName": "developer",
  "lastName":"Port",
  "email": "example@gmail.com",
  "password": "MyPassword123!"
}

In our next article we will develop login functionality ...

Thankyou for reading please follow for more such articles :)