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 };
.png)
.png)