Reputation: 1
When I am trying to save/create a new document (user) to MongoDB using Mongoose, I am getting the following validation error inspite of providing all the values with proper datatypes:
ValidationError: User validation failed: username: Path username is required.
I am a beginner at Node.JS and MongoDB. Hence I am not able to understand what is going wrong.
I have also added the following modules:
Express Mongo Mongoo
VS Code is showing error in signup controller
User validation failed: password: Path
password
is required., fullName: PathfullName
is required., username: Pathusername
is required., gender: Pathgender
is required.
I am facing this problem - please help me solve it. I have shared the code I wrote.
auth.controller.js
:
import User from "../models/user.model.js";
export const signup = async (req, res) => {
try {
const { fullName, username, password, confirmPassword, gender } = req.body;
if (password !== confirmPassword) {
return res.status(400).json({ error: "Passwords don't match" });
}
const user = await User.findOne({ username });
if (user) {
return res.status(400).json({ error: "Username already exists" });
}
// HASH PASSWORD HERE
// https://avatar-placeholder.iran.liara.run/
const boyProfilePic = `https://avatar.iran.liara.run/public/boy?username=${username}`;
const girlProfilePic = `https://avatar.iran.liara.run/public/girl?username=${username}`;
const newUser = new User({
fullName,
username,
gender,
profilePic: gender === "male" ? boyProfilePic : girlProfilePic,
});
await newUser.save();
res.status(201).json({
_id: newUser._id,
fullName: newUser.fullName,
username: newUser.username,
profilePic: newUser.profilePic,
});
} catch (error) {
console.log("Error in signup controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
};
export const login = (req ,res) => {
console.log("login user");
};
export const logout = (req ,res) => {
console.log("logout user");
};
usermodel.js
:
import mongoose from "mongoose";
const userSchema = new mongoose.Schema(
{
fullName: {
type: String,
required: true,
},
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
minlength: 6,
},
gender: {
type: String,
required: true,
enum: ["male", "female"],
},
profilePic: {
type: String,
default: "",
},
// createdAt, updatedAt => Member since <createdAt>
},
{ timestamps: true }
);
const User = mongoose.model("User", userSchema);
export default User;
Please help me solve the problem.
Upvotes: 0
Views: 20