I am summing a decimal column and it is being returned as a string instead of an integer?
exports.sumMoney = function (id) {
return myModel.findAll({
raw: true,
attributes: [[sequelize.fn('SUM', sequelize.col('moneycol')), 'moneylabel']],
where: { id: id }
}).then(r => r);
}
I am summing a decimal column and it is being returned as a string instead of an integer?
exports.sumMoney = function (id) {
return myModel.findAll({
raw: true,
attributes: [[sequelize.fn('SUM', sequelize.col('moneycol')), 'moneylabel']],
where: { id: id }
}).then(r => r);
}
Share
Improve this question
asked Jul 4, 2018 at 2:39
RodRod
15.5k34 gold badges133 silver badges262 bronze badges
1
|
4 Answers
Reset to default 11I'm not sure if you're using MySQL or Postgres, but adding this to the configuration fixed my issue on MySQL
dialectOptions: {
decimalNumbers: true
}
In order to convert result to number you need to perform explicit cast using sequelize.cast function:
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);
}
I don't know why it isn't stated in sequelize v4 docs, but v3 states that:
An explicit cast is required on postgres.
http://sequelize.readthedocs.io/en/v3/api/sequelize/#fnfn-args-sequelizefn
Some days ago i did fix that problem.
Only you need to use SIGNED
instead of int
.
[Transacciones.sequelize.cast(Transacciones.sequelize.fn('SUM', Transacciones.sequelize.col('fare')), 'SIGNED'), 'fare'],
I found two ways to solve it
By Passing get() method in Model
discountPercentage: { type: DataTypes.DECIMAL(18, 3), allowNull: true, defaultValue: 0.000, get() { return parseFloat(this.getDataValue('discountPercentage')) || null; } },
Same as ow3n's answer by setting dialectOptions (I have tried with MySQL)
new Sequelize('mysql://root@localhost:3306/database',{ dialectOptions: { decimalNumbers: true } })
sumMoney
. – Vivek Doshi Commented Jul 4, 2018 at 3:22