I am making a user signup API, where name and email are set to be unique. When I send a JSON object which has a the same email address as an existing user, it gives an error as expected.
But there is no message in that error, which i can then use to give a more usable message.
Below is the error object that i’m getting.
{ "index": 0,
"code": 11000,
"keyPattern": {
"email": 1
},
"keyValue": {
"email": "[email protected]"
}
}
And this is my controller module,
const User=require("../models/userModels.js");
exports.signUp=(req,res)=>{
const user=new User(req.body);
user.save((err,user)=>{
if(err){
res.send(err)
}
else{
res.json({
user
})
}
})
}
2
Answers
Mongoose’s default error object is designed for non limited use cases. So you need to look at it and depending on what it contains add custom messages. For this specific use case of yours, you can for example do it like so:
I’m using
async
/await
syntax here to have a better looking code, yours would work as well.The solution is quite simple, just remove the await before the await
user.save
and boom everything should be fine… but if problem persist then check your username and password in your.env
file and make sure they are correct, also you should make sure your IP address is set to both0.0.0.0
and your current IP in the atlas.Before:
After: