Question

I have a Node.Js Express application and I'm using the Sequelize.js OR/M to query a MySQL 5.6 database. I have a table called homes that contains a couple of bit fields (one of which is called isrental which I have defined as Boolean in the model. When querying the db, these fields always return true even when I have a 0 stored on the record. Here's a quick code example:

var Sequelize = require('sequelize-mysql').sequelize;
var orm = new Sequelize('mysql://procHOAPro:password@NewMasterBedRm/HOAPro'), {
    dialect: 'mysql',
    language: 'en'
});
var Home = orm.define('homes', {
    homeid : Sequelize.INTEGER,
    state : Sequelize.STRING,
    county : Sequelize.STRING,
    city : Sequelize.STRING,
    zip : DataTypes.STRING,
    isrental : {type: Sequelize.BOOLEAN, allowNull: true, defaultValue: false},
    isbuilderowned : {type: Sequelize.BOOLEAN, allowNull: true, defaultValue: false},
    mailingaddress : Sequelize.STRING
});    
Home.all().success(function(homes) {
    console.log(homes[0].isrental);
    console.log(homes[1].isrental);
});

table definition: CREATE TABLE 'homes' ( 'homeid' int(11) NOT NULL AUTO_INCREMENT, 'state' varchar(2) NOT NULL, 'county' varchar(100) NOT NULL, 'city' varchar(100) NOT NULL, 'zip' varchar(5) NOT NULL, 'section' varchar(50) NOT NULL, 'township' int(11) NOT NULL, 'townshipdir' varchar(1) NOT NULL, 'range' int(11) NOT NULL, 'rangedir' varchar(1) NOT NULL, 'block' int(11) NOT NULL, 'lot' int(11) NOT NULL, 'physicaladdress' varchar(255) NOT NULL, 'isrental' bit(1) NOT NULL DEFAULT b'0', 'isbuilderowned' int(1) NOT NULL DEFAULT '0', 'mailingaddress' varchar(255) DEFAULT NULL, PRIMARY KEY ('homeid'), UNIQUE KEY 'homeid_UNIQUE' ('homeid') ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; output:

Executing: SELECT * FROM homes;
true <--this is bs...it's a 0 in the db
true <--this is bs...it's a 0 in the db

As an fyi, I also used the node-orm OR/M and I got the exact same behavior.

Was it helpful?

Solution

Your table definitions seem correct, the error is with sequelize / the way sequelize and node-mysql plays together. Node-mysql returns the bit field as a Buffer instance, but sequelize expects a tinyint. The tinyint can be converted to boolean by double negating it (!!value), whereas double negating a buffer always returns true.

The fix seems pretty easy, just check if the value is a buffer, before trying to convert it to boolean. Could you please create an issue for it on the sequelize github, then I'll hopefully get around to fixing it soon

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top