简体   繁体   中英

Updating data and new object relationship - sequelize

I have this function on my express route that update a user information and its role. The role is another Sequelize Object and I have set up a relationship as one to many:

User.belongsTo(Role);
Role.hasMany(User);

In my route this is my updatefunction:

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

The function works fine updating the info and the new role in the DB, the problem is that the returning User, sometimes doesn't have the updated info, but the previos info. I am not sure if I am implementing this wrong, or trying to update the User model and then asigning a new Role at the the time is breaking something.

Any ideas? Thanks!

Most methods in sequelize are async... I wasn't using my await keywords to let the asynchronos code resolve before moving on.

await modUser.reload();
await modUser.save();

Thanks to @Heiko TheiBen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM