Mike Varela
Mike Varela

Reputation: 527

Sequelize Hook not correctly changing text

I'm using sequelize-cli and have created models which also created migrations. I'm using a hook, beforeCreate, that's working well to lowercase inbound entires to the database. But on an update, the same function, this time called beforeUpdate, (also tried beforeUpsert) isn't working, specifically it's not lowercasing the inbound updated text

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class SoundEffect extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  SoundEffect.init(
    {
      creator: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
      },
      library: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      price: {
        type: DataTypes.NUMBER,
      },
      purchaseDate: {
        type: DataTypes.DATE,
      },
    },
    {
      sequelize,
      modelName: "SoundEffect",
    }
  );

  SoundEffect.beforeCreate(async (soundeffect, options) => {
    soundeffect.creator = soundeffect.creator.toLowerCase().trim();
    soundeffect.library = soundeffect.library.toLowerCase().trim();
  });

  SoundEffect.beforeUpdate(async (soundeffect, options) => {
    soundeffect.creator = soundeffect.creator.toLowerCase().trim();
    soundeffect.library = soundeffect.library.toLowerCase().trim();
  });

  return SoundEffect;
};

Upvotes: 0

Views: 147

Answers (1)

Mike Varela
Mike Varela

Reputation: 527

Found the answer to this, hope it helps other. Basically, the code in the model is right, however, the update REST API function needs another option when updating for this hook to be activated (used). That's the 'individualHooks' set to true.

Below is the Update API function

const updatedItem = await SoundEffect.update(req.body, {
      where: { id: id },
      individualHooks: true,
    });

Upvotes: 0

Related Questions