[ACCEPTED]-Improve mongoose validation error handling-ejs
Accepted answer
In the catch block, you can check if the 4 error is a mongoose validation error, and 3 dynamically create an error object like 2 this:
router.post("/user", async (req, res) => {
try {
var user = new User(req.body);
await user.save();
res.status(200).send(user);
} catch (error) {
if (error.name === "ValidationError") {
let errors = {};
Object.keys(error.errors).forEach((key) => {
errors[key] = error.errors[key].message;
});
return res.status(400).send(errors);
}
res.status(500).send("Something went wrong");
}
});
When we send a request body like this:
{
"email": "test",
"password": "abc"
}
Response 1 will be:
{
"email": "Please enter a valid E-mail!",
"password": "Length of the password should be between 6-1000"
}
you can use validator
like this instead of throwing 1 an error :
password:{
type:String,
required:[true, "Password is a required field"],
validate: {
validator: validator.isLength(value,{min:6,max:1000}),
message: "Length of the password should be between 6-1000"
}
}
you can send
res.status(400).send(error.message);
instead of :
res.status(400).send(error);
and you should 2 make some changes in Schema also.
validate(value){
if (!validator.isEmail(value)) {
throw new Error("Please enter a valid E-mail!");
}
}
with
validate: [validator.isEmail, "Please enter a valid E-mail!" ]
and 1 for password:
minlength: 6,
maxlength:1000,
validate:{
validator: function(el){
return el.toLowerCase() !== "password"
}
message: 'The password should not contain the keyword "password"!'
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.