'Seqelize N:M with Join table update

Currently I have a join table user_roles, user model and the role model, I want to update the role of a particular user after it's initially set.

user_roles - Join table between user and role

<code>db.user = require("../models/user.model.js")(sequelize, Sequelize);
db.role = require("../models/role.model.js")(sequelize, Sequelize);

db.role.belongsToMany(db.user, {
    through: "user_roles",
    foreignKey: "roleId",
    otherKey: "userId"
});
db.user.belongsToMany(db.role, {
    through: "user_roles",
    foreignKey: "userId",
    otherKey: "roleId"
});</code>

User model

<code>
module.exports = (sequelize, Sequelize) => {
    const User = sequelize.define("users", {
        username: {
            type: Sequelize.STRING
        },
        email: {
            type: Sequelize.STRING
        },
        password: {
            type: Sequelize.STRING
        },
        resetPasswordToken: Sequelize.STRING,
        resetPasswordExpires: Sequelize.STRING,
    }); 
    return User; }; </code>

Role Model

<code>module.exports = (sequelize, Sequelize) => {
  const Role = sequelize.define("roles", {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true
    },
    name: {
      type: Sequelize.STRING
    }
  });

  return Role;
};</code>


Solution 1:[1]

Since you have M:N relationship here and use belongsToMany then you can call setRole method of the User model instance to replace roles linked to a certain user by passing role ids there:

await user.setRoles([2])

To add new user roles to existing ones you can use addRole/addRoles. Please look at the official documentation here to see what special methods Sequelize adds to model instances dynamically in case of different types of associations.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anatoly