I have a problem with my code now and I can't make it work. I am trying to check if the email added by the user is already in the database so I can generate an error message to the person and I don't know exactly how to check this. Can someone please help me? Thank you so much
Backend code now:
//Create user
app.post("/register/users", (req, res, next) => {
let userData = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
};
const user = new User(userData);
user
.save()
.then((result) => {
res.status(200).json(result._id);
})
.catch((error) => res.status(422).json(error));
// console.log(res.body);
});
How can I check if user with similar email is already register to display the error? Thank you so much for your time
You can do a check before saving the user.
First, check if the user with the same email exists in the database. If exist, do not save again, instead send the response. If not exist, save the user.
app.post("/register/users", async (req, res, next) => {
let userData = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
};
// checkin if a user with the mail exist
try {
const existingUser = await User.findOne({ email: req.body.email });
if (existingUser) {
// you may want to send different status code
return res.status(200).json({ message: 'User alreay registered });
}
const user = new User(userData);
// save the user
const newUser = await user.save();
return res.status(200).json(newUser._id);
} catch(error) {
return res.status(422).json({ error });
});