I'm trying to make Register using EJS. Therefore, I'm checking
- If all input fields have values or not
- Is Email valid or not
- Password Length has to be < 6 characters
- Is Email already register or not And give them a message if they do not comply with the above conditions. To Check all these conditions I have the following code inside the userCtrl.js file userCtrl.js
const Users = require("../models/userModel");
const userCtrl = {
//! Register User
register: async (req, res) => {
try {
const { name, email, password } = req.body;
// Check If All fields are filled with values or not
if (!name || !email || !password) {
return res.status(400).json({ masg: "Please fill allfields." });
}
// Check If email is valid
if (!validateEmail(email)) {
return res.status(400).json({ masg: "Please enter valid email." });
}
//Check password length
if (password.length < 6) {
return res
.status(400)
.json({ masg: "Password must be atleast 6 characters long." });
}
const user = await Users.findOne({ email });
// Check If email is already registered
if (await Users.findOne({ email })) {
return res.status(400).json({ masg: "User already exists." });
}
res.json({ msg: "User Registered Successfully!" });
} catch (err) {
console.log(err);
return res.status(500).json({ msg: err.message });
}
},
};
//! Exporting User Controller
module.exports = userCtrl;
Here is user Module for refrance.
const mongoose = require("mongoose");
const { Schema } = mongoose;
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Please enter your name"],
trim: true,
},
email: {
type: String,
required: [true, "Please enter your email"],
trim: true,
unique: true,
},
password: {
type: String,
required: [true, "Please enter your password"],
trim: true,
},
role: {
type: Number,
default: 0, // 0 for user, 1 for admin
},
avator: {
type: String,
default:
"https://res.cloudinary.com/manix/image/upload/v1639722719/avator/istockphoto-1214428300-170667a_c4fsdt.jpg",
},
});
//! Exporting User Modules
module.exports = mongoose.model("Users", userSchema);
But when I try to register users using Postman then I got this error. enter image description here
Please Help me to fix this issue.