Skip to content

Commit

Permalink
fix(discriminator): make base schema paths come before discriminator …
Browse files Browse the repository at this point in the history
…schema paths when running setters, validators, etc.

Fix #13794
  • Loading branch information
vkarpov15 committed Sep 9, 2023
1 parent f552fe2 commit b36fd11
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/helpers/discriminator/mergeDiscriminatorSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ module.exports = function mergeDiscriminatorSchema(to, from, path, seen) {
key === 'base' ||
key === '_applyDiscriminators' ||
key === '_userProvidedOptions' ||
key === 'options') {
key === 'options' ||
key === 'tree') {
continue;
}
}
Expand Down
1 change: 1 addition & 0 deletions lib/helpers/model/discriminator.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
}

mergeDiscriminatorSchema(schema, baseSchema);
schema.tree = Object.assign({}, baseSchema.tree, schema.tree);

// Clean up conflicting paths _after_ merging re: gh-6076
for (const conflictingPath of conflictingPaths) {
Expand Down
23 changes: 23 additions & 0 deletions test/model.discriminator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2180,4 +2180,27 @@ describe('model', function() {
assert.ok(innerBuildingsPath.schemaOptions.type.discriminators.Garage);
assert.equal(innerBuildingsPath.schemaOptions.type.discriminators.Garage.discriminatorMapping.value, 'G');
});

it('runs base schema paths validators and setters before child schema validators and setters (gh-13794)', async function() {
const baseSchema = new Schema({
f1: {
type: Number,
set() {
return 1;
}
}
});
const childSchema = new Schema({
f2: {
type: Number,
set() {
return this.f1;
}
}
});
const Test = db.model('Test', baseSchema);
const Child = Test.discriminator('Child', childSchema);
const doc = new Child({ f1: 2, f2: 2 });
assert.strictEqual(doc.f2, 1);
});
});
2 changes: 1 addition & 1 deletion test/types/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1217,4 +1217,4 @@ function gh13800() {
expectType<string>(this.lastName);
expectError<string>(this.someOtherField);
});
}
}

0 comments on commit b36fd11

Please sign in to comment.