Sequelize 将整数作为字符串返回

Sequelize is returning integer as string

我使用带有 sequelize 的 nodejs v4,我有一个这样的模型:

var Device = sequelize.define('Device', {
id: {
  type: DataTypes.BIGINT,
  primaryKey: true,
  autoIncrement: true
},
tenantId: {
  type: DataTypes.BIGINT,
  allowNull: false
},
token: {
  type: DataTypes.STRING,
  allowNull: false
}
}, {
 tableName: 'devices'
});

当我通过idselect一个设备时,id的类型是字符串,例如:

Device.findById(9).then( function(result) {
  console.log(result.toJSON().id + 10);
});

输出将是 910,而不是 19,所以我查看 json 并看到了这个:

{
  id: "9"
  tenantId: "123"
  token: "adsadsdsa"
}

found device里面的id是字符串,我定义为数字...

不应该是 { "id": 9 } 吗?

如何 select 具有我之前定义的类型的设备?

默认情况下,sequelize 会尝试格式化您的结果。您可以设置raw :true获取原始数据

我在 sequelize 存储库中找到了解决此问题的方法。

https://github.com/sequelize/sequelize/issues/4523

用于 sequelize 的 pg 模块 returns bigint as string 因为 bigints 不能保证适合 js 数字。所以我将我的模型更改为使用整数 (DataTypes.INTEGER)

BIGINT 最大值为 2^63-1,javascript 最多可以安全地表示 2^53。为了安全起见,库 return 将这些数字作为字符串。

如果你想要数字而不是字符串,你可以使用这个库 https://github.com/mirek/node-pg-safe-numbers 来处理这个问题。

IMO,一个更流畅的解决方案是强制将 int 解析为 int,而不是字符串。签出 this issue and comments.

试图将这一行放在你的逻辑代码对我有用之前,这会强制将 int8 解析为 int,而不是字符串:

require("pg").defaults.parseInt8 = true;

...

try {
    const list = await Posts.findAll();
    console.log(JSON.stringify(list));
} catch (e) {
    console.log(e.message);
}