Skip to content

Commit

Permalink
Merge pull request #13846 from Automattic/vkarpov15/gh-13794
Browse files Browse the repository at this point in the history
fix(discriminator): make base schema paths come before discriminator schema paths when running setters, validators, etc.
  • Loading branch information
vkarpov15 committed Sep 15, 2023
2 parents 6d0b072 + 7b5b354 commit 71fce29
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
7 changes: 6 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 Expand Up @@ -73,4 +74,8 @@ module.exports = function mergeDiscriminatorSchema(to, from, path, seen) {
mergeDiscriminatorSchema(to[key], from[key], path ? path + '.' + key : key, seen);
}
}

if (from != null && from.instanceOfSchema) {
to.tree = Object.assign({}, from.tree, to.tree);
}
};
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);
});
});

0 comments on commit 71fce29

Please sign in to comment.