How to get rows with a bit typed fields from mysql in node.js?
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.
This may be late, but there is a way to cast BIT fields to booleans right when you define the connection (or pool):
var pool = mysql.createPool({
"connectionLimit": process.env.MYSQL_LIMIT,
"user": process.env.MYSQL_USER,
"password": process.env.MYSQL_PASSWORD,
"database": process.env.MYSQL_DATABASE,
"host": process.env.MYSQL_HOST,
"port": process.env.MYSQL_PORT,
"typeCast": function castField( field, useDefaultTypeCasting ) {
// We only want to cast bit fields that have a single-bit in them. If the field
// has more than one bit, then we cannot assume it is supposed to be a Boolean.
if ( ( field.type === "BIT" ) && ( field.length === 1 ) ) {
var bytes = field.buffer();
// A Buffer in Node represents a collection of 8-bit unsigned integers.
// Therefore, our single "bit field" comes back as the bits '0000 0001',
// which is equivalent to the number 1.
return( bytes[ 0 ] === 1 );
}
return( useDefaultTypeCasting() );
}
});
This was adapted from this article: https://www.bennadel.com/blog/3188-casting-bit-fields-to-booleans-using-the-node-js-mysql-driver.htm