diff --git a/lib/schemaType.js b/lib/schemaType.js index ee8c9a6aeeb..ae64712f823 100644 --- a/lib/schemaType.js +++ b/lib/schemaType.js @@ -59,7 +59,9 @@ function SchemaType(path, options, instance) { const defaultOptionsKeys = Object.keys(defaultOptions); for (const option of defaultOptionsKeys) { - if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) { + if (option === 'validate') { + this.validate(defaultOptions.validate); + } else if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) { options[option] = defaultOptions[option]; } } diff --git a/test/schematype.test.js b/test/schematype.test.js index 38691d645ae..582a135c09c 100644 --- a/test/schematype.test.js +++ b/test/schematype.test.js @@ -208,6 +208,37 @@ describe('schematype', function() { }); }); + it('merges default validators (gh-14070)', function() { + class TestSchemaType extends mongoose.SchemaType {} + TestSchemaType.set('validate', checkIfString); + + const schemaType = new TestSchemaType('test-path', { + validate: checkIfLength2 + }); + + assert.equal(schemaType.validators.length, 2); + assert.equal(schemaType.validators[0].validator, checkIfString); + assert.equal(schemaType.validators[1].validator, checkIfLength2); + + let err = schemaType.doValidateSync([1, 2]); + assert.ok(err); + assert.equal(err.name, 'ValidatorError'); + + err = schemaType.doValidateSync('foo'); + assert.ok(err); + assert.equal(err.name, 'ValidatorError'); + + err = schemaType.doValidateSync('ab'); + assert.ifError(err); + + function checkIfString(v) { + return typeof v === 'string'; + } + function checkIfLength2(v) { + return v.length === 2; + } + }); + describe('set()', function() { describe('SchemaType.set()', function() { it('SchemaType.set, is a function', () => {