travega
travega

Reputation: 8415

Sequelize - map fields to field alias in model definition

I am defining a Sequelize model to map fields from existing tables in my database. However, the field names in the table are long and not developer-friendly.

Is it possible to map the database field names to aliases in the model definition so that my service has more developer-friendly model property names to work with?

Example:

This...

// Horrible field names
module.exports = (sequelize, DataTypes) =>
  sequelize.define('Transaction', {
    f_curr_finaccount__amount: DataTypes.DECIMAL,
    f_curr_finaccount__tx_type: DataTypes.STRING,
    f_finaccount__currency_iso_id: DataTypes.STRING,
    f_lex_finaccount__tx_atomic_status: DataTypes.STRING
  }, {
    schema: 'fins',
    tableName: 'fins_financialaccounttransaction',
    timestamps: false
  })

...becomes...

// Developer-friendly field names
module.exports = (sequelize, DataTypes) =>
  sequelize.define('Transaction', {
    amount: {
      type: DataTypes.DECIMAL,
      fieldName: 'f_curr_finaccount__amount'
    },
    type: {
      type: DataTypes.STRING,
      fieldName: 'f_curr_finaccount__tx_type'
    },
    currency: {
      type: DataTypes.STRING,
      fieldName: 'f_finaccount__currency_iso_id'
    },
    status: {
      type: DataTypes.STRING,
      fieldName: 'f_lex_finaccount__tx_atomic_status'
    }
  }, {
    schema: 'fins',
    tableName: 'fins_financialaccounttransaction',
    timestamps: false
  })

Upvotes: 4

Views: 3227

Answers (1)

Ellebkey
Ellebkey

Reputation: 2301

Exactly as you did but the name of the attribute is just field. It will be the same for all columns including foreign keys.

// Developer-friendly field names
module.exports = (sequelize, DataTypes) =>
  sequelize.define('Transaction', {
    amount: {
      type: DataTypes.DECIMAL,
      field: 'f_curr_finaccount__amount'
    },
    type: {
      type: DataTypes.STRING,
      field: 'f_curr_finaccount__tx_type'
    },
    currency: {
      type: DataTypes.STRING,
      field: 'f_finaccount__currency_iso_id'
    },
    status: {
      type: DataTypes.STRING,
      field: 'f_lex_finaccount__tx_atomic_status'
    }
  }, {
    schema: 'fins',
    tableName: 'fins_financialaccounttransaction',
    timestamps: false
  })

Upvotes: 4

Related Questions