Search code examples
sequelize.jscamelcasingsnakecasing

How to mix sequelize camel case and snake case?


Using Sequelize 6, I have a model, associated with tables, that has capital letters in some columns and snake case in others (the columns are not created_at or updated_at).

The underscored model configuration seems to affect each attribute associated with the corresponding table columns. Is there a way to override the model level underscored configuration such that the the attribute associated with the table column retains the original column name of the table?

Code example:

  const someModel = sequelize.define('some_table', {
    'id': {
      type: dataTypes.BIGINT,
      primaryKey: true,
      autoIncrement: true,
    },
    'other_table_id': {
      type: dataTypes.BIGINT,
      allowNull: false,
      references: {
        model: 'other_table',
        key: 'id',
        deferrable: INITIALLY_IMMEDIATE,
      },
    },
    'CAPITAL_letterColumn': {
      type: dataTypes.STRING,
      allowNull: true,
      defaultValue: null,,
    }
  }, {
      timestamps: false,
      paranoid: false,
      // underscored: true, // true === snake case, false === camelcase
    }
  });

  someModel.associate = (models) => {
    someModel.belongsTo(models.other_table, { foreignKey: 'other_table_id', targetKey: 'id' });
  };

I get the following error:

UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column "otherTableId" does not exist

If I set

underscored: true

I get the following error:

UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column "c_a_p_i_t_a_l_letter_column" of relation "some_table" does not exist

Solution

  • Looks like adding the field attribute in model definition fixes the issue.

    'other_table_id': {
      field: 'other_table_id', // <-- this line 
      type: dataTypes.BIGINT,
      allowNull: false,
      references: {
        model: 'other_table',
        key: 'id',
        deferrable: INITIALLY_IMMEDIATE,
      },
    },