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.

User1

"username":"test1"
"email":"test1@gmail.com"

Change it to this one

User 1

"username":"test2"
"email":"test1@gmail.com"

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, “test1@gmail.com” 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})


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")
        }

 }

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 newUser.save() during the very short time period between the findOne() of the first user and its newUser.save(). 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 req.body.email 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.