Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rows with a bit typed fields from mysql in node.js?

Tags:

node.js

mysql

I am using a mysql npm package for connection and trying to get data from table, which has columns with type BIT. But these columns have gone as:

"isBasic": {
      "type": "Buffer",
      "data": [
        1
      ]
    },

How can I map them to boolean type?

like image 511
Sergiy Avatar asked Dec 22 '15 11:12

Sergiy


People also ask

What is RowDataPacket in node JS?

RowDataPacket is actually the name of the constructor function that creates an object, it would look like this new RowDataPacket(user_id, ...) . You can check by accessing its name [0].constructor.name. If the result is an array, you would have to use [0].


2 Answers

The bit data type is not perfectly used in mysql package. We usually use tinyint in tables to store 0 and 1 and then just do the comparison in Javscript to determine true or false.

like image 82
bdifferent Avatar answered Sep 27 '22 20:09

bdifferent


Here is how you can read type=BIT value:

bit.lastIndexOf(1) !== -1

I've tested with true and false values:

console.log(bit, ' ----> ', bit.lastIndexOf(1) !== -1);
console.log(bit, ' ----> ', bit.lastIndexOf(1) !== -1);

// out:   <Buffer 01> ' ----> ' true
// out:   <Buffer 00> ' ----> ' false

And another way is to add transformation into SQL query:

mysql_connection.query('SELECT *,field_name=1 as field_name ...

and field_name's value will be 1 if true and 0 for false.

like image 44
Lukas Liesis Avatar answered Sep 27 '22 22:09

Lukas Liesis