Skip to content

Commit

Permalink
feat(schematype): merge rather than overwrite default schematype vali…
Browse files Browse the repository at this point in the history
…dators

Fix #14070
  • Loading branch information
vkarpov15 committed Nov 27, 2023
1 parent 29f4da7 commit ae961ff
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/schemaType.js
Expand Up @@ -59,7 +59,19 @@ 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') {
const defaultValidators = Array.isArray(defaultOptions.validate)
? defaultOptions.validate
: defaultOptions.validate == null
? []
: [defaultOptions.validate];
const specifiedValidators = Array.isArray(options.validate)
? options.validate
: options.validate == null
? []
: [options.validate];
options.validate = [...defaultValidators, ...specifiedValidators];
} else if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) {
options[option] = defaultOptions[option];
}
}
Expand Down
19 changes: 19 additions & 0 deletions test/schematype.test.js
Expand Up @@ -208,6 +208,25 @@ describe('schematype', function() {
});
});

it('merges default validators (gh-14070)', function() {
class TestSchemaType extends mongoose.SchemaType {}
TestSchemaType.set('validate', v => typeof v === 'string');

const schemaType = new TestSchemaType();
schemaType.validate(v => v.length === 2);

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

describe('set()', function() {
describe('SchemaType.set()', function() {
it('SchemaType.set, is a function', () => {
Expand Down

0 comments on commit ae961ff

Please sign in to comment.