Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic default value for Sequelize model

Tags:

sequelize.js

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.

like image 427
Brad Avatar asked Jul 11 '15 20:07

Brad


1 Answers

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.

like image 124
cattail Avatar answered Sep 28 '22 17:09

cattail