Skip to content

Commit ae961ff

Browse files
committed
feat(schematype): merge rather than overwrite default schematype validators
Fix #14070
1 parent 29f4da7 commit ae961ff

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

lib/schemaType.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,19 @@ function SchemaType(path, options, instance) {
5959
const defaultOptionsKeys = Object.keys(defaultOptions);
6060

6161
for (const option of defaultOptionsKeys) {
62-
if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) {
62+
if (option === 'validate') {
63+
const defaultValidators = Array.isArray(defaultOptions.validate)
64+
? defaultOptions.validate
65+
: defaultOptions.validate == null
66+
? []
67+
: [defaultOptions.validate];
68+
const specifiedValidators = Array.isArray(options.validate)
69+
? options.validate
70+
: options.validate == null
71+
? []
72+
: [options.validate];
73+
options.validate = [...defaultValidators, ...specifiedValidators];
74+
} else if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) {
6375
options[option] = defaultOptions[option];
6476
}
6577
}

test/schematype.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,25 @@ describe('schematype', function() {
208208
});
209209
});
210210

211+
it('merges default validators (gh-14070)', function() {
212+
class TestSchemaType extends mongoose.SchemaType {}
213+
TestSchemaType.set('validate', v => typeof v === 'string');
214+
215+
const schemaType = new TestSchemaType();
216+
schemaType.validate(v => v.length === 2);
217+
218+
let err = schemaType.doValidateSync([1, 2]);
219+
assert.ok(err);
220+
assert.equal(err.name, 'ValidatorError');
221+
222+
err = schemaType.doValidateSync('foo');
223+
assert.ok(err);
224+
assert.equal(err.name, 'ValidatorError');
225+
226+
err = schemaType.doValidateSync('ab');
227+
assert.ifError(err);
228+
});
229+
211230
describe('set()', function() {
212231
describe('SchemaType.set()', function() {
213232
it('SchemaType.set, is a function', () => {

0 commit comments

Comments
 (0)