1

I have created "blogs" table with id(primary key), title ,created at ,updated at , status (with enum type having values "active,inactive,hidden" with default value "active")

create function on Blog Model is working fine when giving status value from above mentioned set of values and empty value

const Blog = sequelize.define('blog', { id: { type: 
Sequelize.INTEGER, 
primaryKey: true, autoIncrement: true }, text: Sequelize.STRING, 
status : { type : Sequelize.ENUM, allowNull : false, values : 
['Inactive','Active','Hidden'], defaultValue : 'Active' } }); 
Blog.create({"title" :"hello","status":"abc"}).then(result => {
console.log(result);
});

The above code inserted a new record in blogs table with status of empty value.but result object having status of "abc".How can I get newly inserted record ?

3
  • Share your model definition Commented Aug 29, 2019 at 11:15
  • Blog = sequelize.define('blog', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, text: Sequelize.STRING, status : { type : Sequelize.ENUM, allowNull : false, values : ['Inactive','Active','Hidden'], defaultValue : 'Active' } }); Commented Aug 29, 2019 at 11:27
  • Please update the question to keep model definition as part of it. Commented Aug 29, 2019 at 11:30

1 Answer 1

3

You should define ENUM like this:

status : { 
  type : Sequelize.ENUM('Inactive','Active','Hidden'), 
  allowNull : false, 
  defaultValue : 'Active',
  validate: {
    isIn: { 
      args: [['Inactive','Active','Hidden']],
      msg: "Wrong status"
    }
  }
}

In order to validate enum values you can use per attribute validation

Sign up to request clarification or add additional context in comments.

3 Comments

I don't need to validate.Create function output object is not same as database inserted record.When I try to insert a new record with status value of "abc" , it inserted in blogs table with empty value but output object contain "abc".
It's not the same, because database does "validation" and does not allow other values to be inserted. Also by default INSERT query does not return newly inserted record, so Sequelize can't return it back to you either.
If you don't want to validate, but still want to be able to insert invalid data, then you can implement custom getter that will cut out all values except defined list. But I'm not sure if it's good practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.