I have developed a function within my Express route that is responsible for updating user information as well as their assigned role. The role itself is represented by another Sequelize Object, and I have established a one-to-many relationship between the two:
User.belongsTo(Role);
Role.hasMany(User);
Within my route, this is how the updatefunction is structured:
const UpdateUser = async user => {
if (Object.keys(user).length !== 0) {
const { id, firstName, lastName, phone, email, role } = user;
let modUser = await User.findOne({ where: { id }, include: [{ model: Role}] });
if (modUser.firstName !== firstName) modUser.firstName = firstName;
if (modUser.lastName !== lastName) modUser.lastName = lastName;
if (modUser.phone !== phone) modUser.phone = phone;
if (modUser.email !== email && UniqueEmail(email)) modUser.email = email;
if(modUser.Role.id !== role) {
await modUser.setRole(await Role.findByPk(role));
}
modUser.save();
modUser = await User.findOne(
{
where: { id },
include: [{ model: Role}],
attributes: { exclude: ['RoleId', 'password'] }
},
);
return modUser.reload();
}
return { error: "No user found" };
}
Although the function successfully updates user information and role in the database, there seems to be an issue with the returned User occasionally not reflecting the updated details but rather showing previous information. I am uncertain whether my implementation is incorrect, or if attempting to simultaneously update the User model and assign a new Role may be causing a conflict.
Any insights on how to resolve this? Thank you!