Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!