My Collection.save() function is working fine and identifying duplicate key values. But, when duplicate values occur , I am not able to get the entire error message as response.
My User.save function
const user = new User({
first_name,
last_name,
email,
username,
password: cryptedPassword,
bYear,
bDay,
bMonth,
gender,
}).save(function (err, data) {
if (data) {
console.log("inside save then data");
return res.status(200).send(data);
} else {
console.log("inside save then err");
return res.status(200).send(err);
}
});
My console message
(if I remove the else part
But when I try to send the err message as response json, I get only the below response in my postman
{
"index": 0,
"code": 11000,
"keyPattern": {
"email": 1
},
"keyValue": {
"email": "[email protected]"
}
}
How to get the full error message, so that i can intimate the duplicate key issue.
2
Answers
First, I recommend using async/await. In catch, you can check if the error is a duplicate key error or not, and you can create custom error messages. Also, return statusCode 400 instead of 200.
According to mongoose docs, when an error is throw, you can check for the
msg
property.Below is a full example