Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize js with big integers

I have an application written in Node JS and uses the Sequelize js ORM library to access my database which is MySql.

My problem is that I have a column in my db which is BIGINT and when the value of it is large I get wrong values when I retrieve it.

for example when the value in database is: 10205918797953057 I get 10205918797953056 when I get it using sequelize.

I tried using big-integer library but I had no luck.

any advice is welcomed.

P.S: I can't change the datatype to VARCHAR.

like image 751
Sami Avatar asked Feb 10 '15 13:02

Sami


2 Answers

You should enable supportBigNumbers and possibly bigNumberStrings on the mysql module: https://github.com/felixge/node-mysql#connection-options

new Sequelize(..., {
  dialect: 'mysql',
  dialectOptions: {
    supportBigNumbers: true
  }
});
like image 182
Jan Aagaard Meier Avatar answered Oct 05 '22 23:10

Jan Aagaard Meier


The answer by Jan Aagaard Meier is correct and works, But there are few things to consider.

According to Sequelize Docs (connection-options):

supportBigNumbers: When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option (Default: false).

bigNumberStrings: Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately represented with JavaScript Number objects(which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects. This option is ignored if supportBigNumbers is disabled.

So, in some cases, to handle the returned value correctly, using both bigNumberStrings and supportBigNumbers might be a better option that guarantees a string value in return.

like image 33
Bishwajyoti Roy Avatar answered Oct 05 '22 23:10

Bishwajyoti Roy