Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize is returning integer as string

I using nodejs v4 with sequelize, and I have a model like this:

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'
});

When I select a device by id the type of id is a string, exemple:

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

The output will be 910, rather than 19, so I look at json and a saw this:

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

The id in found device is a string, but I defined it as a number...

Doesn't it should be { "id": 9 } ?

How can I select a device with the types that I defined previously?

like image 317
Lucas Merencia Avatar asked Sep 12 '15 21:09

Lucas Merencia


People also ask

How do I set default value in Sequelize?

When you create a Sequelize model, you can add the default value for your model by adding the defaultValue option to the column(s) definition. The defaultValue option will be used by Sequelize to define default value(s) for your SQL column(s) when you create a table using Sequelize.

What is UUID Sequelize?

Extends: src/data-types.js~ABSTRACT → UUID. A column storing a unique universal identifier.

How do you define varchar in Sequelize?

If you give the datatype as TEXT in Sequelize It will automatically convert that field to NVARCHAR(MAX ) for SQL Server database.


2 Answers

I found a fix to this problem on sequelize repo.

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

The pg module used for sequelize returns bigint as string because bigints are not guaranteed to fit into js numbers. So I change my model to use integer (DataTypes.INTEGER)

like image 175
Lucas Merencia Avatar answered Sep 20 '22 16:09

Lucas Merencia


BIGINT maximum value is 2^63-1, javascript can safely represent up to 2^53. To be on the safe side libraries return those numbers as strings.

If you want to have numbers instead of strings, you can use this library https://github.com/mirek/node-pg-safe-numbers which deals with this issue.

like image 27
Mirek Rusin Avatar answered Sep 22 '22 16:09

Mirek Rusin