user3254198
user3254198

Reputation: 759

sequelize.js - set column value on create

What I'm trying to do here is automatically set a column value when the entry gets created.

So let's say that if I were to have a Posts table which has the columns: :id :integer :primary :title :string :post :text :slug :string :unique

and I create a new entry of this with sequelize by calling Model.Posts.create then I want the slug column to be automatically set to a value (the title slugified) when it gets created without having to do anything.

How would I have this be done?

Upvotes: 1

Views: 1353

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28798

You could use a beforeCreate hook:

sequelize.define('post', attributes, {
    hooks: {
        beforeCreate: function (instance) {
            instance.set('slug', slugify(instance.get('title'));
        }
    }
});

Upvotes: 1

Related Questions