1

I am trying to create a hook that should get called after the primary key is created for the record. I am trying to generate a number using a combination of the columns that were inserted, including the primary key. The instance hook seems to get called whereas the global hook is not getting called, hewever the field keep coming back null even though I am seeing the hook is called:

module.exports = function(sequelize, DataTypes) {
  var store = sequelize.define('store', {
    storenumber: DataTypes.STRING(30), //remove
    storespecificationid: DataTypes.INTEGER,
    storetypeid: DataTypes.INTEGER,
    storename: DataTypes.STRING(20), //remove
    address: DataTypes.STRING(30),
    city: DataTypes.STRING(30),
    state: DataTypes.STRING(30),
    zipcode: DataTypes.STRING(30)
  }, {
    classMethods: {
      associate: function(models) {
          // associations can be defined here
      },
      hooks: {
      /*this is not getting called*/
          afterCreate: function(store){
              let strnumber = store.storetypeid + store.storespecificationid + store.id;
              store.updateAttributes({ storenumber:  strnumber });
          }
      }
    }
  });

  /*
  This seems to be called
  store.afterCreate(function(store) {
      let strnumber = store.storetypeid + store.storespecificationid + store.id;
              store.updateAttributes({ storenumber:  strnumber });
    });
    */

  return store;
};

Can someone shed some light on what I am doing wrong?

1 Answer 1

1

i think you have one extra object defined classMethods

Try the schema below

   module.exports = function(sequelize, DataTypes) {
   var store = sequelize.define('store', {
    storenumber: DataTypes.STRING(30), //remove
    storespecificationid: DataTypes.INTEGER,
    storetypeid: DataTypes.INTEGER,
    storename: DataTypes.STRING(20), //remove
    address: DataTypes.STRING(30),
    city: DataTypes.STRING(30),
    state: DataTypes.STRING(30),
    zipcode: DataTypes.STRING(30)
  }, {

      associate: function(models) {
          // associations can be defined here
      },
      hooks: {
      /*this is not getting called*/
          afterCreate: function(store){
              let strnumber = store.storetypeid + store.storespecificationid + store.id;
              store.updateAttributes({ storenumber:  strnumber });
          }
      }

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

Comments

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.