Sequelize - Update a date field automatically on an event

410 views Asked by At

I've a login table which stores the user login details. Whenever a user changes the password, lastPasswordChange field should get updated with the date of the password change. Now I'm manually updateing the field with Date().

Is there any better way to do this in Sequelize. Node.js and Mysql DB

1

There are 1 answers

0
Sudhir Bastakoti On

you can use beforeSave(instance, options) hook in your model, like:

...
YourModel.addHook('beforeSave', async (modelInstance) => {
    // if password change is detected
    if (instance.changed('password')) {
      instance.lastPasswordChange= new Date();
    }
});