I'm trying to update a user email at MongoDB, but I need to verify previously if this e-mail does not exist yet. In my Schema, I have:
const UserSchema = new Schema({
fullName: { type: String, required: true },
email: { type: String, unique: true, required: true }
});
And in my controller:
exports.update = (req, res) => {
const entries = Object.keys(req.body);
const updates = {};
for (let i = 0; i < entries.length; i = 1) {
updates[entries[i]] = Object.values(req.body)[i];
}
const userId = req.body._id ? req.body._id : req.userId;
User.updateOne({ _id: userId }, { $set: updates }).exec((err, data) => {
if (err) {
res.status(500).send({ message: "Failed!" });
return;
}
if (data.n === 0) {
res.status(404).send({ message: "Not Found!" });
return;
}
res.status(200).send({ message: "Success!" });
});
};
It's working well, but if I enter an email already used, I get to update. How can I prevent it?
CodePudding user response:
Since you are using unique: true
in your schema you can update the value and only will return success
if it is not duplicated.
By the way, if you want to return a message error specific if the email
exists you can check if the error is the code 11000
.
Something like this:
User.updateOne({ _id: userId }, { $set: updates }).exec((err, data) => {
if (err) {
if(err.code === 11000){
return res.status(400).send({ message: "Uniques values already exists"});
} else {
return res.status(500).send({ message: "Failed!" });
}
}
if (data.n === 0) {
res.status(404).send({ message: "Not Found!" });
return;
}
res.status(200).send({ message: "Success!" });
});