Skip to content

Commit ddd6f83

Browse files
authored
Merge pull request #15142 from Automattic/vkarpov15/gh-15120
fix(schema): allow multiple self-referencing discriminator schemas using Schema.prototype.discriminator
2 parents f025b29 + 02915de commit ddd6f83

3 files changed

Lines changed: 32 additions & 0 deletions

File tree

lib/schema/documentArray.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,7 @@ SchemaDocumentArray.prototype.clone = function() {
522522
}
523523
schematype.Constructor.discriminators = Object.assign({},
524524
this.Constructor.discriminators);
525+
schematype._appliedDiscriminators = this._appliedDiscriminators;
525526
return schematype;
526527
};
527528

lib/schema/subdocument.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,5 +393,6 @@ SchemaSubdocument.prototype.clone = function() {
393393
schematype.requiredValidator = this.requiredValidator;
394394
}
395395
schematype.caster.discriminators = Object.assign({}, this.caster.discriminators);
396+
schematype._appliedDiscriminators = this._appliedDiscriminators;
396397
return schematype;
397398
};

test/model.test.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8004,6 +8004,36 @@ describe('Model', function() {
80048004
assert.equal(doc.items[0].prop, 42);
80058005
});
80068006

8007+
it('does not throw with multiple self-referencing discriminator schemas applied to schema (gh-15120)', async function() {
8008+
const baseSchema = new Schema({
8009+
type: { type: Number, required: true }
8010+
}, { discriminatorKey: 'type' });
8011+
8012+
const selfRefSchema = new Schema({
8013+
self: { type: [baseSchema] }
8014+
});
8015+
8016+
const anotherSelfRefSchema = new Schema({
8017+
self2: { type: [baseSchema] }
8018+
});
8019+
8020+
baseSchema.discriminator(5, selfRefSchema);
8021+
baseSchema.discriminator(6, anotherSelfRefSchema);
8022+
const Test = db.model('Test', baseSchema);
8023+
8024+
const doc = await Test.create({
8025+
type: 5,
8026+
self: {
8027+
type: 6,
8028+
self2: null
8029+
}
8030+
});
8031+
assert.strictEqual(doc.type, 5);
8032+
assert.equal(doc.self.length, 1);
8033+
assert.strictEqual(doc.self[0].type, 6);
8034+
assert.strictEqual(doc.self[0].self2, null);
8035+
});
8036+
80078037
it('inserts versionKey even if schema has `toObject.versionKey` set to false (gh-14344)', async function() {
80088038
const schema = new mongoose.Schema(
80098039
{ name: String },

0 commit comments

Comments
 (0)