node.jssequelize.js

On update time Sequelize hook not trigger


I have add beforeCreate and beforeUpdate hook in sequelize model

hooks: {
      beforeCreate: (Coach) => {
        Coach.password = getBcryptHashPassword(Coach.password);
      },
      beforeUpdate: (Coach) => {
        if (Coach.password)
          Coach.password = getBcryptHashPassword(Coach.password);
      },
    },

Create time hook treigger properly

But when I can update service hook not trigger

exports.update = async (data, conditions) => {
  return Model.update(data,conditions );
};

This is my update service

I want trigger beforeUpdate hook on call update service


Solution

  • If you want to use in controller

    exports.update = async (req, res, next) => {
      try {
        const data = await service.update(req.body, {
          where: {
            id: req.params.id,
            academyId: req.user.id,
          },
          individualHooks: true
        });
    
    
        res.status(200).json({
          status: "success",
          message: "Update successfully.",
          affectedRows: data,
        });
      } catch (error) {
        next(error);
      }
    };