Hello everyone,
I have a schema in which the username is unique. When I add the user if the username already exists the API gives the error and is working fine. However, when I want to update the user details I can not update the name because it is still giving me the username that already exists as it is in the database if I remove the validation in the update API the username is no more unique than. Can anybody know the solution? How to update the fields with a unique name and email?
const updateUser = async function (req, res) {
const { username, firstName, lastName, age } = req.body;
try {
const user = await User.findById(req.params.id)
if (!user) {
return res.status(400).send('user not found');
}
if(user.username) {
return res.status(400).send('user already exists.');
}
questions.username = username;
questions.firstName = firstName
user.lastName = lastName
questions.age = age
const updateUser = await user.save()
return res.json(updateQuestions);
} catch (err) {
return res.status(500).send('Something went wrong. Try again ' + err);
}
};