13

How can I create a default value that is generated programmatically upon creation of a new instance of a Sequelize model? I've read how to do this somewhere, but can't find it anywhere. I thought this had something to do with classMethods, but I can't figure out what that method should be called.

For example:

sequelize.define('Account', {
  name: DataTypes.STRING
}, {
  classMethods: {
    something: function (instance) {
      instance.name = 'account12345';
    }
  }
});

models.account.create(function (account) {
  console.log(account.name); // Echos "account12345" or whatever I
});

If you could point me in the right direction, it would be greatly appreciated.

1 Answer 1

24

You can just define defaultValue as function, sequelizejs explained in http://docs.sequelizejs.com/en/v3/api/datatypes/, the example code is

sequelize.define('model', {
  uuid: {
    type: DataTypes.UUID,
    defaultValue: function() {
      return generateMyId()
    },
    primaryKey: true
  }
})

However, you can't get the instance because before the defaultValue generated we don't have the instance.

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

2 Comments

@MuhammadUmer you have to make sure it's unique by yourself.
@cattail How about if I'm adding a column, therefore the instance is already available. Can I get set the value of a different column as the defaultValue?

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.