Correctly handle validatesUniquenessOf(idName)

This commit is contained in:
Fabien Franzen 2015-07-13 12:56:25 +02:00
parent 64b6aef924
commit 6ce47f71b4
2 changed files with 30 additions and 0 deletions

View File

@ -342,11 +342,15 @@ function validateUniqueness(attr, conf, err, done) {
}, this); }, this);
} }
var idName = this.constructor.definition.idName();
var isNewRecord = this.isNewRecord();
this.constructor.find(cond, function (error, found) { this.constructor.find(cond, function (error, found) {
if (error) { if (error) {
err(error); err(error);
} else if (found.length > 1) { } else if (found.length > 1) {
err(); 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())) { } else if (found.length === 1 && (!this.id || !found[0].id || found[0].id.toString() != this.id.toString())) {
err(); err();
} }

View File

@ -19,6 +19,8 @@ function getValidAttributes() {
describe('validations', function () { describe('validations', function () {
var User, Entry;
before(function (done) { before(function (done) {
db = getSchema(); db = getSchema();
User = db.define('User', { User = db.define('User', {
@ -34,6 +36,11 @@ describe('validations', function () {
createdByScript: Boolean, createdByScript: Boolean,
updatedAt: Date updatedAt: Date
}); });
Entry = db.define('Entry', {
id: { type: 'string', id: true, generated: false },
name: { type: 'string' }
});
Entry.validatesUniquenessOf('id');
db.automigrate(done); db.automigrate(done);
}); });
@ -436,6 +443,25 @@ describe('validations', function () {
done(); done();
})).should.be.false; })).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 () { describe('format', function () {