Skip to content

Commit

Permalink
fix(schema): allow multiple self-referencing discriminator schemas using
Browse files Browse the repository at this point in the history
Schema.prototype.discriminator

Fix #15120
  • Loading branch information
vkarpov15 committed Jan 1, 2025
1 parent f025b29 commit 02915de
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/schema/documentArray.js
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,7 @@ SchemaDocumentArray.prototype.clone = function() {
}
schematype.Constructor.discriminators = Object.assign({},
this.Constructor.discriminators);
schematype._appliedDiscriminators = this._appliedDiscriminators;
return schematype;
};

Expand Down
1 change: 1 addition & 0 deletions lib/schema/subdocument.js
Original file line number Diff line number Diff line change
Expand Up @@ -393,5 +393,6 @@ SchemaSubdocument.prototype.clone = function() {
schematype.requiredValidator = this.requiredValidator;
}
schematype.caster.discriminators = Object.assign({}, this.caster.discriminators);
schematype._appliedDiscriminators = this._appliedDiscriminators;
return schematype;
};
30 changes: 30 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8004,6 +8004,36 @@ describe('Model', function() {
assert.equal(doc.items[0].prop, 42);
});

it('does not throw with multiple self-referencing discriminator schemas applied to schema (gh-15120)', async function() {
const baseSchema = new Schema({
type: { type: Number, required: true }
}, { discriminatorKey: 'type' });

const selfRefSchema = new Schema({
self: { type: [baseSchema] }
});

const anotherSelfRefSchema = new Schema({
self2: { type: [baseSchema] }
});

baseSchema.discriminator(5, selfRefSchema);
baseSchema.discriminator(6, anotherSelfRefSchema);
const Test = db.model('Test', baseSchema);

const doc = await Test.create({
type: 5,
self: {
type: 6,
self2: null
}
});
assert.strictEqual(doc.type, 5);
assert.equal(doc.self.length, 1);
assert.strictEqual(doc.self[0].type, 6);
assert.strictEqual(doc.self[0].self2, null);
});

it('inserts versionKey even if schema has `toObject.versionKey` set to false (gh-14344)', async function() {
const schema = new mongoose.Schema(
{ name: String },
Expand Down

0 comments on commit 02915de

Please sign in to comment.