Improve mongoose validation error handling
In the catch block, you can check if the error is a mongoose validation error, and dynamically create an error object like 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 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 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 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 for password:
minlength: 6,maxlength:1000,validate:{validator: function(el){return el.toLowerCase() !== "password"}message: 'The password should not contain the keyword "password"!'}