Manuel
Manuel

Reputation: 9522

Sequelize hook afterUpdate How to get dirty fields, original value and updated value?

I'm stuck with sequelize hooks, trying to write every change to a model into a log table. Therefore I'm looking for a way to access the models data before and after the write to MySQL.

How can I access this data within Sequelize Hook afterUpdate?

How can I get the updated/changed/dirty fields?

How can I access data before and after the update to make diffs?

Upvotes: 6

Views: 9086

Answers (3)

serguitus
serguitus

Reputation: 526

Use instance.dataValues and instance._previousDataValues to access values after and before object update. This is valid for instance hooks, not bulk hooks. taken from Sequelize Hooks- Previous data values for afterBulkUpdate

Upvotes: 1

wl1711
wl1711

Reputation: 1

    module.exports = (sequelize, DataTypes) => {
        const ContractLineItem = sequelize.define('ContractLineItem', {
            id: {
                type: DataTypes.INTEGER,
                field: 'id',
                allowNull: false,
                primaryKey: true,
                autoIncrement: true
            }
            //more attributes here
        }, {
            schema: 'public',
            tableName: 'ContractLineItem',
            timestamps: true
        });


        ContractLineItem.beforeBulkUpdate((contractLineItem, options) => {    
            console.log("b4 update contractLineItem....contractLineItem._change =" + contractLineItem._change);

            if (!contractLineItem._change){
                console.log("nothing changed.............");
                //skip updating record
                //return next();
            }else{
                console.log("something changed................");
                //update record
            }
            console.log("after checking on change....");
        });

        ContractLineItem.associate = (models) => {

            ContractLineItem.belongsTo(models.Contract, {
                foreignKey: 'contractId',
            });
            //more relationships

        };
        return ContractLineItem;
    };

Upvotes: 0

Manuel
Manuel

Reputation: 9522

Hook functions first argument is instance. As long as instance is fetched ahead of update operation, instance._previousDataValues and instance._change are available.

sequelize.addHook(
  "afterCreate",
  (i) => {
    console.log(i);
  }
);

Upvotes: 8

Related Questions