How can I accept user input if he only wants to change a specific input?

Hello guys, I’ve been having a lot of trouble with how can I work on this. Basically, I want the user to update his information.

So example, I have a user.



Change it to this one

User 1


So in this scenario, User1, wants to change his username to “test2” only, and let his email stays the same.

But the problem is, his email, “” is already existing in the database, so when he saves it, it gets an error because the email is already existing.

Now the question is, How can I allow the user to change his information either username or email, but still save his default information?

const userExist = await User.findOne({username})
const emailExist = await User.findOne({email})

     res.status(400).json("User Already Existing...")
}else if(emailExist){
    res.status(400).json("Email Already Exists...")
      try {
            const newUser = new User({
                username: req.body.username,
                studentid: req.body.studentid,
                password: CryptoJS.AES.encrypt(
            const savedUser = await
        } catch (error) {
            return  res.status(400).json("Error Login")


Some might suggest, just remove the validation for email, but I also want the same function to email, I want the user to choose whatever he picks and update it, but still save the other input box to its current value

You are doing something fundamentally wrong in terms of database.

You are testing for the existence of things with User.findOne() before updating. In a database, another user might try to perform the same update and run its during the very short time period between the findOne() of the first user and its You might end up with duplicate.

Indexes with uniqueness exists for that purpose. You do your update and you handle correctly the duplicate value exception thrown by the server.

Any reason why you define username and email as used in User.findOne() but still use req.body.username and in new User().

Finally, your database access code is mangled with your UI code. That makes it very hard to unit test. But that might be okay since with res.status(200).json(savedUser) this code might be a web API. But I still prefer separation of concerns.