user1790300
user1790300

Reputation: 1735

Implementing triggers using node.js sequelize and hooks

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?

Upvotes: 1

Views: 1538

Answers (1)

Asif Saeed
Asif Saeed

Reputation: 2045

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 });
          }
      }

  });

Upvotes: 1

Related Questions