简体   繁体   English

更新数据和新的 object 关系 - sequelize

[英]Updating data and new object relationship - sequelize

I have this function on my express route that update a user information and its role.我的快速路线上有这个 function 更新用户信息及其角色。 The role is another Sequelize Object and I have set up a relationship as one to many:角色是另一个 Sequelize Object,我已经建立了一对多的关系:

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. function 可以很好地更新数据库中的信息和新角色,问题是返回的用户有时没有更新的信息,而是以前的信息。 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.我不确定我是否正在实施这个错误,或者尝试更新用户 model 然后在当时分配一个新角色会破坏某些东西。

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. sequelize 中的大多数方法都是异步的...我没有使用我的 await 关键字让异步代码在继续之前解析。

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

Thanks to @Heiko TheiBen感谢@Heiko TheiBen

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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