Skip to content

Commit

Permalink
fix(discriminator): shallow clone Schema.prototype.obj before mergi…
Browse files Browse the repository at this point in the history
…ng schemas to avoid modifying original obj

Fix #14827
  • Loading branch information
vkarpov15 committed Aug 28, 2024
1 parent 16df3da commit 9526e66
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/helpers/model/discriminator.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
}
}

// Shallow clone `obj` so we can add additional properties without modifying original
// schema. `Schema.prototype.clone()` copies `obj` by reference, no cloning.
schema.obj = { ...schema.obj };
mergeDiscriminatorSchema(schema, baseSchema);

// Clean up conflicting paths _after_ merging re: gh-6076
Expand Down
17 changes: 17 additions & 0 deletions test/model.discriminator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,23 @@ describe('model', function() {
Person.discriminator('Parent2', parentSchema.clone());
});

it('clone() does not modify original schema `obj` (gh-14821)', function() {
const personSchema = new Schema({
name: String
}, { discriminatorKey: 'kind' });

const parentSchema = new Schema({
child: String
});

const Person = db.model('Person', personSchema);
const Parent = Person.discriminator('Parent', parentSchema.clone());

assert.ok(!Person.schema.obj.child);
assert.ok(!personSchema.obj.child);
assert.ok(Parent.schema.obj.child);
});

it('clone() allows reusing with different models (gh-5721)', async function() {
const schema = new mongoose.Schema({
name: String
Expand Down

0 comments on commit 9526e66

Please sign in to comment.