diff --git a/lib/mysql.js b/lib/mysql.js index 38d76aa..8547fad 100644 --- a/lib/mysql.js +++ b/lib/mysql.js @@ -324,6 +324,9 @@ MySQL.prototype.toDatabase = function (prop, val, forCreate) { return this.client.escape(val); } if (prop.type === Number) { + if (isNaN(val)) { + return 'NULL'; + } return this.client.escape(val); } if (prop.type === Date) { @@ -508,7 +511,11 @@ MySQL.prototype._buildWhere = function (model, conds) { sqlCond += (condType === 'inq' || condType === 'nin') ? '(' + val + ')' : val; cs.push(sqlCond); } else { - cs.push(keyEscaped + ' = ' + val); + if (val === 'NULL') { + cs.push(keyEscaped + ' IS NULL'); + } else { + cs.push(keyEscaped + ' = ' + val); + } } }); if (cs.length === 0) { @@ -595,6 +602,19 @@ MySQL.prototype.all = function all(model, filter, callback) { }; +MySQL.prototype.find = function find(model, id, callback) { + var idName = this.idName(model); + var filter = {where: {}, limit: 1}; + filter.where[idName] = id; + this.all(model, filter, function(err, results) { + if (err) { + return callback && callback(err); + } else { + return callback && callback(results && results[0]); + } + }); +}; + MySQL.prototype.count = function count(model, callback, where) { this.query('SELECT count(*) as cnt FROM ' + diff --git a/test/mysql.test.js b/test/mysql.test.js index af1c3dc..a86b3c3 100644 --- a/test/mysql.test.js +++ b/test/mysql.test.js @@ -455,6 +455,18 @@ describe('mysql', function () { }); }); + it('should convert NaN to NULL for query', function(done) { + Post.create({title: 'My Post1', content: 'Hello', stars: 5}, + function(err, post) { + Post.findById('x', + function(err, post) { + should.not.exist(err); + should.not.exist(post); + done(); + }); + }); + }); + it('should not allow duplicate titles', function (done) { var data = {title: 'a', content: 'AAA'}; PostWithUniqueTitle.create(data, function (err, post) {