Reputation: 15
Stack: NodeJs, PostgreSQL, Sequelize, Express. I have two associated models (User and Role) through User_Roles. When I create new user via Sequelize.create(), how can i fill the User_Roles table to define which roles (i get the array filled with role ID) the user have. The roles are already defined in table (roles)
The models:
const User = sequelize.define('users', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
email: { type: DataTypes.STRING(320), allowNull: false, unique: true, isEmail: true },
});
const Role = sequelize.define('roles', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
title: { type: DataTypes.STRING(64), allowNull: false, unique: true },
});
const User_Roles = sequelize.define('user_roles', {}, { timestamps: false });
// Associations
User.belongsToMany(Role, { through: User_Roles });
Role.belongsToMany(User, { through: User_Roles });
UserController:
async create(req, res, next) {
const { email, roles } = req.body;
if (!email) {
return next(ApiError.badRequest('Invalid request'));
}
if (!Array.isArray(roles) || !roles.length) {
return next(ApiError.badRequest('Invalid request'));
}
const isExistThisEmail = await User.findOne({ where: { email } });
if (isExistThisEmail) {
return next(ApiError.badRequest('The email already exists'));
}
const user = await User.create({ email });
return res.status(201).json(createdUser);
}
Upvotes: 0
Views: 80
Reputation: 22803
You can use dynamically added methods (according to associations) in the model:
await user.setRoles([1,2,3]) // or indicate the roles instances
Upvotes: 2