Back to Courses

World's Best MERN Stack Course

MERN #10: Storing Registered User Data in an Online Database with Express and Mongoose πŸ”₯

Welcome, to our MERN Stack Tutorial, where we guide you through the process of saving user data in an online database using Express and Mongoose! πŸŒπŸ’Ύ Learn how to retrieve and destructure user data from req.body, check for existing email entries, and seamlessly store user information in the database. Join us on this hands-on journey of storing and managing user data with practical examples and Postman testing! πŸš€

auth-controller.js

const User = require("../models/auth-model");

// *-------------------
// Home Logic
// *-------------------
const home = async (req, res) => {
  try {
    res.status(200).json({ msg: "Welcome to our home page" });
  } catch (error) {
    console.log(error);
  }
};

// *-------------------------------
//* User Registration Logic πŸ“
// *-------------------------------
// 1. Get Registration Data: πŸ“€ Retrieve user data (username, email, password).
// 2. Check Email Existence: πŸ“‹ Check if the email is already registered.
// 3. Hash Password: πŸ”’ Securely hash the password.
// 4. Create User: πŸ“ Create a new user with hashed password.
// 5. Save to DB: πŸ’Ύ Save user data to the database.
// 6. Respond: βœ… Respond with "Registration Successful" or handle errors.

const register = async (req, res) => {
  try {
    // const data = req.body;
    console.log(req.body);
    const { username, email, phone, password } = req.body;

    const userExist = await User.findOne({ email: email });

    if (userExist) {
      return res.status(400).json({ msg: "email already exists" });
    }

    const userCreated = await User.create({ username, email, phone, password });

    // res.status(201).json({ message: "User registered successfully" });
    res.status(201).json({ msg: userCreated });
  } catch (error) {
    res.status(500).json({ message: "Internal server error" });
  }
};

module.exports = { home, register };