I’ve been struggling with what logic should I put on this one. I want the user to update his information, but I’m encountering a problem.
What if the user wants to change his/her email, but keeps his username? In this case, since his username is already existing in the backend. vice-versa
Like example, I have this data.
"username": "test1",
"email": "[email protected]"
The user only wants to update his username and save his default email.
"username":"test1updated",
"email":"[email protected]"
And since I’m using a validation that,
const userExist = await User.findOne({username})
const emailExist = await User.findOne({email})
if(userExist){
res.status(400).json("User Already Existing...")
}else if(emailExist){
res.status(400).json("Email Already Exists...")
}else{
try {
const newUser = new User({
username: req.body.username,
email: req.body.email,
studentid: req.body.studentid,
password: CryptoJS.AES.encrypt(
req.body.password,
'secret_key',
).toString(),
});
const savedUser = await newUser.save()
res.status(200).json(savedUser)
} catch (error) {
return res.status(400).json("Error Login")
}
}
This means that it will not save since its existing and my mongoose only accepts unique input, How can I allow the user to update his chosen information, like update username only without changing the email?
Some might suggest, just remove the validation for email, but I also want the same function to email.
Or should I make the username unchangeable? since it’s my login information?
2
Answers
Lets say that a user has a unique identifier of sort, that being a auto increment value in database or some other id.
The
userExist
could be updated to find a username where the unique id does not match the current users id effectively removing the current user from check query.Other method would be to save users old information(either hidden elements on UI or db query with users id) before he changes it and then check what was changed and what was not changed.
First option would be better.
I suppose you know what is the current username and email. On save check if username or email is changed, if changed only then try to do validation and save. If data is not even changed there is no point in validating and saving it.