Skip to content

Commit

Permalink
fix(model): make recompileSchema() overwrite existing document arra…
Browse files Browse the repository at this point in the history
…y discriminators

Fix #14520
  • Loading branch information
vkarpov15 committed Apr 27, 2024
1 parent 5137eeb commit 3072c41
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/schema/documentArray.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ SchemaDocumentArray.prototype.discriminator = function(name, schema, options) {
schema = schema.clone();
}

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

const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor);
EmbeddedDocument.baseCasterConstructor = this.casterConstructor;
Expand Down
17 changes: 17 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7463,6 +7463,23 @@ describe('Model', function() {
assert.equal(instance.item.whoAmI(), 'I am Test2');
});

it('overwrites existing discriminators when calling recompileSchema (gh-14527) (gh-14444)', async function() {
const shopItemSchema = new mongoose.Schema({}, { discriminatorKey: 'type' });
const shopSchema = new mongoose.Schema({
items: { type: [shopItemSchema], required: true }
});

const shopItemSubType = new mongoose.Schema({ prop: Number });
shopItemSchema.discriminator(2, shopItemSubType);
const shopModel = db.model('shop', shopSchema);

shopModel.recompileSchema();
const doc = new shopModel({
items: [{ type: 2, prop: 42 }]
});
assert.equal(doc.items[0].prop, 42);
});

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 3072c41

Please sign in to comment.