Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda