I have a seemingly common problem with sequelize. For context I am trying to assign a default role
to each user
that is created. Essentially each user
's role should be set to default user
when they are first registered.
I would like to be able to simply define this default value in my Models file as you would with normal fields but, I can't seem to find the correct syntax.
This is what my User model currently looks like:
'use strict';
import { Sequelize } from 'sequelize';
export default (sequelize: Sequelize) => {
const Users = sequelize.define(
'Users',
{
email: {
type: Sequelize.STRING,
allowNull: false
},
some_foreign_id: {
type: Sequelize.STRING,
allowNull: false
}
},
{}
);
Users.associate = models => {
// associations can be defined here
Users.belongsTo(models.Roles, { as: 'Role' });
};
return Users;
};
Currently I am just making a query to find the role
with the name default role
and adding it to my user as it is created. However, I feel that query is unnecessary.
Based on the google autofill suggestions it seems like a lot of people have this problem without any clear solution.
[EDIT]
My role
model (heh) currently looks like this:
import { Sequelize } from 'sequelize';
export default (sequelize: Sequelize) => {
const Roles = sequelize.define(
'Roles',
{
name: {
type: Sequelize.STRING,
allowNull: false
}
},
{}
);
Roles.associate = models => {
// associations can be defined here
// SO note: This association is for my permissions. Should have nothing to do with my User association.
Roles.belongsToMany(models.Permissions, { through: 'RolePermission' });
};
return Roles;
};