Merge pull request #664 from fabien/fix/validate-uniqueness

Correctly handle validatesUniquenessOf(idName)
This commit is contained in:
Raymond Feng 2015-07-13 09:45:59 -07:00
commit cf1dee2d64
2 changed files with 30 additions and 0 deletions

View File

@ -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();
}

View File

@ -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 () {