Answer the question
In order to leave comments, you need to log in
What is the best way to update unique fields in MongoDb?
Hi all.
Task. The user can change his data: name, age, email, phone number. At the same time, email and phone are unique fields. If the user tries to replace the email or number with an existing one, then he needs to display an adequate message about this. If the mail is busy by someone, the message will be - "mail is busy", if the number - "number is busy".
Problem. When I try to replace the email with an existing one, the entry in the database is not updated, which is good, but the backend crashes, stops, and I need to display a message to the user, and so that the backend continues to work.
Possible Solution. The very first thing that comes to mind. Consecutive steps
1. Check if the email and phone on the frontend have changed. If not, then we can safely update the data in the database.
2. If the email and/or phone number have changed, then before saving them, you first need to check whether a user with such email already exists in the database. If not, then ok, but then you need to make another request to check if such a user with a phone number exists.
It turns out two more. request. And their number increases with the number of unique fields being changed. Somehow not optimal or normal?
Question Is there a better solution?
Answer the question
In order to leave comments, you need to log in
Pseudocode:
User.findOneAndUpdate({_id: "1s3d21f2s1d3f2s1d32f1"}, {
email: "[email protected]",
number: "123456789"
}, (err, user) => {
if(err) { // проверяйте что за ошибка и если ошибка уникального поля, то уведомляйте юзера
return res.status(400).json({error: err});
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question