Skip to content

Commit 3072c41

Browse files
committed
fix(model): make recompileSchema() overwrite existing document array discriminators
Fix #14520
1 parent 5137eeb commit 3072c41

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

lib/schema/documentArray.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ SchemaDocumentArray.prototype.discriminator = function(name, schema, options) {
195195
schema = schema.clone();
196196
}
197197

198-
schema = discriminator(this.casterConstructor, name, schema, tiedValue);
198+
schema = discriminator(this.casterConstructor, name, schema, tiedValue, null, null, options?.overwriteExisting);
199199

200200
const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor);
201201
EmbeddedDocument.baseCasterConstructor = this.casterConstructor;

test/model.test.js

+17
Original file line numberDiff line numberDiff line change
@@ -7463,6 +7463,23 @@ describe('Model', function() {
74637463
assert.equal(instance.item.whoAmI(), 'I am Test2');
74647464
});
74657465

7466+
it('overwrites existing discriminators when calling recompileSchema (gh-14527) (gh-14444)', async function() {
7467+
const shopItemSchema = new mongoose.Schema({}, { discriminatorKey: 'type' });
7468+
const shopSchema = new mongoose.Schema({
7469+
items: { type: [shopItemSchema], required: true }
7470+
});
7471+
7472+
const shopItemSubType = new mongoose.Schema({ prop: Number });
7473+
shopItemSchema.discriminator(2, shopItemSubType);
7474+
const shopModel = db.model('shop', shopSchema);
7475+
7476+
shopModel.recompileSchema();
7477+
const doc = new shopModel({
7478+
items: [{ type: 2, prop: 42 }]
7479+
});
7480+
assert.equal(doc.items[0].prop, 42);
7481+
});
7482+
74667483
it('inserts versionKey even if schema has `toObject.versionKey` set to false (gh-14344)', async function() {
74677484
const schema = new mongoose.Schema(
74687485
{ name: String },

0 commit comments

Comments
 (0)