Skip to content

Commit 33e3898

Browse files
authored
Merge pull request #14124 from Automattic/vkarpov15/gh-14070-2
feat(schematype): merge rather than overwrite default schematype validators
2 parents 29f4da7 + da8462e commit 33e3898

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

lib/schemaType.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,9 @@ 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+
this.validate(defaultOptions.validate);
64+
} else if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) {
6365
options[option] = defaultOptions[option];
6466
}
6567
}

test/schematype.test.js

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

211+
it('merges default validators (gh-14070)', function() {
212+
class TestSchemaType extends mongoose.SchemaType {}
213+
TestSchemaType.set('validate', checkIfString);
214+
215+
const schemaType = new TestSchemaType('test-path', {
216+
validate: checkIfLength2
217+
});
218+
219+
assert.equal(schemaType.validators.length, 2);
220+
assert.equal(schemaType.validators[0].validator, checkIfString);
221+
assert.equal(schemaType.validators[1].validator, checkIfLength2);
222+
223+
let err = schemaType.doValidateSync([1, 2]);
224+
assert.ok(err);
225+
assert.equal(err.name, 'ValidatorError');
226+
227+
err = schemaType.doValidateSync('foo');
228+
assert.ok(err);
229+
assert.equal(err.name, 'ValidatorError');
230+
231+
err = schemaType.doValidateSync('ab');
232+
assert.ifError(err);
233+
234+
function checkIfString(v) {
235+
return typeof v === 'string';
236+
}
237+
function checkIfLength2(v) {
238+
return v.length === 2;
239+
}
240+
});
241+
211242
describe('set()', function() {
212243
describe('SchemaType.set()', function() {
213244
it('SchemaType.set, is a function', () => {

0 commit comments

Comments
 (0)