Jamie Jamie - 11 months ago 607
Node.js Question

Sequelize updating nested associations

I have an instance where I have Users and Roles. I have the following:

var User = sequelize.define("Users", {
username: DataTypes.STRING,
password: DataTypes.STRING,

var Role = sequelize.define("Role", {
role: DataTypes.STRING

var UsersRole = sequelize.define("UsersRole");

User.belongsToMany(Role, {through: UsersRole});

Which creates a UsersRoles table in the DB for me with a UserId and RoleId column. This is all working fine, but now I want to be able to update a users role, I can't work out quite how to do this! I've tried the following with no luck so far:

where: { id: req.params.id },
include: [{ all: true }]
RoleId: req.body.role,
where: { UserId : req.params.id }
).then(function (result) {...

In summary, all I want to do is be able to change a users role, so update the 'UsersRoles' table and change the RoleId for a given UserId. I can't quite seem to figure out how to get to the UsersRoles table via any sequelize syntax!

I could write some raw SQL but that doesn't feel right?


I just want to update a users role, if the table has:

| UserId | RoleId |
| 1 | 1 |

I would like to be able to change it to:

| UserId | RoleId |
| 1 | 2 |

but I can't quite figure out the code to do this!


There is no need to interact with the join table directly - You can simply do



Notice that I'm passing an array, since users can have many roles - set removes all currently assigned roles. If you want to add a new role and keep the existing, use