Sequelize在结果对象中混合驼峰和蛇形键

时间:2019-01-07 02:49:14

标签: javascript node.js sequelize.js

我试图从Sequelize create(或任何Sequelize查询)中获取结果纯对象,使其始终成为蛇格键。但是结果对象是混合的。这是一个示例查询:

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

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

结果对象是驼峰和蛇格的混合键:

{
    "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
}

有什么主意如何将结果纯对象或嵌套对象完全设为蛇格键?将package.json中的sequelize从^ 4.42.0升级到^ 5.0.0-beta,并且两者都发生。不知道还有什么尝试?

Accounts表是所有蛇案列名:

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)
  },

帐户模型中的选项带有以下划线:true和camelCase attrs,在蛇案中具有字段

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 个答案:

答案 0 :(得分:0)

现在我用以下方法解决它:

import snakeCaseKeys from 'snakecase-keys'

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