cerberus
cerberus

Reputation: 561

What is the best way to handle big number returning from database in nodeJS?

I have a node JS application getting data from MySql Database. Column type of one the column is bigint(20). This will return a big integer value and this is going out of javascript number range. What is the best way to handle this?

Sample code

let rows = database.query("select resourcekey from resourceTable");

for(var i = 0; i < rows.length; i++) {
  console.log(rows[i].resourcekey);
}

Sample resourceKey : 9220610450398789367 Value returned : 9220610450398790000

Upvotes: 0

Views: 2775

Answers (2)

cerberus
cerberus

Reputation: 561

NodeJS mysql provides supportBigNumbers and bigNumberStrings configuration options. Enabling both of this will force to return big numbers(BIGINT and Decimal) to be returned as javascript string.

let dbConnection = mysql.createConnection({supportBigNumbers: true, bigNumberStrings: true});

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

Since you are making your calculations on the programming side, i.e., Node JS, store the content as VARCHAR(50) and parse it as Integer in Node JS:

for(var i = 0; i < rows.length; i++) {
  console.log(parseInt(rows[i].resourcekey));
}

MySQL is messing up the huge integer value and you don't require unless you are performing mathematical operations in the MySQL Server itself.

Upvotes: 0

Related Questions