Javascript 为什么我的sequelize查询将十进制列求和作为字符串返回

Javascript 为什么我的sequelize查询将十进制列求和作为字符串返回,javascript,node.js,sequelize.js,Javascript,Node.js,Sequelize.js,我对一个十进制列求和,它将作为字符串而不是整数返回 exports.sumMoney = function (id) { return myModel.findAll({ raw: true, attributes: [[sequelize.fn('SUM', sequelize.col('moneycol')), 'moneylabel']], where: { id: id } }).then(r => r); } 为了

我对一个十进制列求和,它将作为字符串而不是整数返回

exports.sumMoney = function (id) {
    return myModel.findAll({
        raw: true,
        attributes: [[sequelize.fn('SUM', sequelize.col('moneycol')), 'moneylabel']],
        where: { id: id }
    }).then(r => r);
}

为了将结果转换为数字,您需要使用sequelize.cast函数执行显式转换:

exports.sumMoney = function (id) {
    return myModel.findAll({
        raw: true,
        attributes: [[sequelize.cast(sequelize.fn('SUM', sequelize.col('moneycol')), 'int'), 'moneylabel']],
        where: { id: id }
    }).then(r => r);
}
我不知道为什么sequelize v4文档中没有说明,但v3声明:

postgres需要显式强制转换


我不确定您使用的是MySQL还是Postgres,但将其添加到配置中修复了我在MySQL上的问题

dialectOptions: {
    decimalNumbers: true
}

几天前我确实解决了这个问题。 只有您需要使用
SIGNED
而不是
int

[Transacciones.sequelize.cast(Transacciones.sequelize.fn('SUM', Transacciones.sequelize.col('fare')), 'SIGNED'), 'fare'],

我找到了两种解决方法

  • 通过在模型中传递get()方法

    discountPercentage: {
     type: DataTypes.DECIMAL(18, 3),
     allowNull: true,
     defaultValue: 0.000,
     get() {
       return parseFloat(this.getDataValue('discountPercentage')) || null;
     }
    },
    
  • 通过设置方言选项,与ow3n的答案相同(我用MySQL尝试过)


  • 请发布
    coursey
    的输出。谢谢您的回答。对我来说效果很好。
    new Sequelize('mysql://root@localhost:3306/database',{ 
      dialectOptions: 
       { 
         decimalNumbers: true 
       }
    })