The software default for the Sequelize model

How do I create a default that is generated programmatically when a new instance of the Sequelize model is created? I've read how to do this somewhere, but can't find it anywhere. I thought it had something to do with classMethods

, but I can't figure out what this method should be calling.

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 helpful.

+3


source to share


2 answers


You can just define defaultValue as a function, sequelizejs described at http://docs.sequelizejs.com/en/v3/api/datatypes/ , example code

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

      



However, you cannot get an instance, because we don't have an instance before generating the defaultValue.

+3


source


just add the defaultValue field to your model attribute, something like this:



sequelize.define('Account', {
  name: { 
        type : DataTypes.STRING,
        defaultValue : "account12345"
 }
}

      

-2


source







All Articles