Sequelize mixes camel case and snake case keys in result object

Viewed 1759

Am trying to get the resulting plain object from Sequelize create (or any Sequelize query) to be snake case keys throughout. The result objects are mixed however. Here's an example query:

const object = await models.Account.create({
  userId,
  name,
  accountNumber
})

console.log(object.get({ plain: true }))

The result object is mixed keys of camel case and snake case:

{
    "id": 2,
    "userId": 1,
    "name": "baller",
    "accountNumber": "1234-123-1234",
    "updated_at": "2019-01-07T02:23:41.305Z",
    "created_at": "2019-01-07T02:23:41.305Z",
    "balance": "0.00",
    "deleted_at": null
}

Any idea how to get the result plain object or nested objects to be completely snake case keys only? Upgrade sequelize from ^4.42.0 to ^5.0.0-beta in package.json and happens for both. Not sure what else to try?

Accounts table is all snake case column names:

return queryInterface.createTable('accounts', {
  id: {
    allowNull: false,
    autoIncrement: true,
    primaryKey: true,
    type: Sequelize.INTEGER
  },
  user_id: {
    allowNull: false,
    type: Sequelize.INTEGER,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  name: {
    allowNull: false,
    type: Sequelize.STRING(50)
  },
  account_number: {
    allowNull: false,
    type: Sequelize.STRING(50)
  },

Account model has has option underscored: true and camelCase attrs with field in snake case

const Account = sequelize.define('Account', {
  userId: {
    type: DataTypes.INTEGER,
    field: 'user_id',
    allowNull: false,
    validate: {
      notNull(value) {
        if (value == null) {
          throw new Error('Missing user id')
        }
      }
    }
  },
  name: {
    type: DataTypes.STRING,
    field: 'name',
    validate: {
      notEmpty: true
    }
  },
  accountNumber: {
    type: DataTypes.STRING,
    field: 'account_number',
    validate: {
      notEmpty: true
    }
  },
}, {
  tableName: 'accounts',
  paranoid: true,
  underscored: true
})
1 Answers

For now I'm resolving it with:

import snakeCaseKeys from 'snakecase-keys'

let jsonObject = object.get({ plain: true })
jsonObject = snakeCaseKeys(jsonObject)
Related