Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default value on sequelize ENUM type

I am currently trying to set default value on a column with type ENUM, however if i set the defaultValue to "employee" which is one of the values of the enum, I get the below error message:

$ npx sequelize db:migrate

Sequelize CLI [Node: 10.16.0, CLI: 5.5.0, ORM: 5.15.1]

Loaded configuration file "src\config\config.js".
Using environment "development".
== 20190824180419-create-user: migrating =======

ERROR: invalid input value for enum "enum_Users_role": "employee"

Find bellow my user migration file definition

20190824180419-create-user.js


export default {
  up: (queryInterface, Sequelize) => queryInterface.createTable('Users', {
    uuid: {
    allowNull: false,
    primaryKey: true,
    type: Sequelize.UUID,
    defaultValue: Sequelize.UUIDV4,
  },
  email: {
    type: Sequelize.STRING
  },
  password: {
    type: Sequelize.STRING
  },
  name: {
    type: Sequelize.STRING
  },
  role: {
    type: Sequelize.ENUM,
    values: ['employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'],
    defaultValue: 'employee'
  }
}),
down: queryInterface => queryInterface.dropTable('Users')

};

Find bellow my user model file definition:

user.js

export default (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    uuid: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true
    },
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    name: DataTypes.STRING,
    role: {
      type: DataTypes.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),
      defaultValue: 'employee'
     }
  }, {});
  User.associate = () => {
   // associations can be defined here
  };
  return User;
};

Package versions:

node: v10.16.0
npm: 6.9.0
sequelize: 5.15.1
sequelize-cli: 5.5.0
like image 204
wokoro douye samuel Avatar asked Aug 29 '19 10:08

wokoro douye samuel


2 Answers

You are setting ENUM values wrong. It should be like you did in model definition via ENUM constructor:

{
  type: Sequelize.DataTypes.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),
  defaultValue: 'employee',
}
like image 172
rkm Avatar answered Oct 31 '22 22:10

rkm


Can you remove the defaultValue in the model and change the format as @rkm mentioned. So you have something like this:

role: DataTypes.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),

and in your migration file as:

role: {
      type: Sequelize.ENUM('employee', 'super_admin', 'travel_admin', 'travel_team_manager', 'manager', 'supplier'),
defaultValue: 'employee'
     }
like image 30
tvpeter Avatar answered Oct 31 '22 22:10

tvpeter