diff --git a/lib/validations.js b/lib/validations.js index 102e04a6..db9ef1fe 100644 --- a/lib/validations.js +++ b/lib/validations.js @@ -342,11 +342,15 @@ function validateUniqueness(attr, conf, err, done) { }, this); } + var idName = this.constructor.definition.idName(); + var isNewRecord = this.isNewRecord(); this.constructor.find(cond, function (error, found) { if (error) { err(error); } else if (found.length > 1) { err(); + } else if (found.length === 1 && idName === attr && isNewRecord) { + err(); } else if (found.length === 1 && (!this.id || !found[0].id || found[0].id.toString() != this.id.toString())) { err(); } diff --git a/test/validations.test.js b/test/validations.test.js index d0e59f40..2f64bcc1 100644 --- a/test/validations.test.js +++ b/test/validations.test.js @@ -19,6 +19,8 @@ function getValidAttributes() { describe('validations', function () { + var User, Entry; + before(function (done) { db = getSchema(); User = db.define('User', { @@ -34,6 +36,11 @@ describe('validations', function () { createdByScript: Boolean, updatedAt: Date }); + Entry = db.define('Entry', { + id: { type: 'string', id: true, generated: false }, + name: { type: 'string' } + }); + Entry.validatesUniquenessOf('id'); db.automigrate(done); }); @@ -436,6 +443,25 @@ describe('validations', function () { done(); })).should.be.false; }); + + it('should work with id property on create', function (done) { + Entry.create({ id: 'entry' }, function(err, entry) { + var e = new Entry({ id: 'entry' }); + Boolean(e.isValid(function (valid) { + valid.should.be.false; + done(); + })).should.be.false; + }); + }); + + it('should work with id property after create', function (done) { + Entry.findById('entry', function(err, e) { + Boolean(e.isValid(function (valid) { + valid.should.be.true; + done(); + })).should.be.false; + }); + }); }); describe('format', function () {