Skip to content

Commit 404b74b

Browse files
committed
fix: infer discriminator key if set in $set with overwriteDiscriminatorKey
Re: #15218
1 parent 16d2407 commit 404b74b

File tree

3 files changed

+19
-5
lines changed

3 files changed

+19
-5
lines changed

CHANGELOG.md

-2
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,6 @@
123123
* fix: disallow using $where in match
124124
* perf: cache results from getAllSubdocs() on saveOptions, only loop through known subdoc properties #15055 #15029
125125
* fix(model+query): support overwriteDiscriminatorKey for bulkWrite updateOne and updateMany, allow inferring discriminator key from update #15046 #15040
126-
=======
127-
>>>>>>> 7.x
128126

129127
7.8.3 / 2024-11-26
130128
==================

lib/helpers/query/castUpdate.js

+10
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,16 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
8282
schema = schema.discriminators[discriminatorValue] ||
8383
(byValue && byValue.schema) ||
8484
schema;
85+
} else if (schema != null &&
86+
options.overwriteDiscriminatorKey &&
87+
obj.$set != null &&
88+
utils.hasUserDefinedProperty(obj.$set, schema.options.discriminatorKey) &&
89+
schema.discriminators != null) {
90+
const discriminatorValue = obj.$set[schema.options.discriminatorKey];
91+
const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
92+
schema = schema.discriminators[discriminatorValue] ||
93+
(byValue && byValue.schema) ||
94+
schema;
8595
}
8696

8797
if (options.upsert) {

test/model.test.js

+9-3
Original file line numberDiff line numberDiff line change
@@ -4174,7 +4174,7 @@ describe('Model', function() {
41744174
assert.strictEqual(r2.testArray[0].nonexistentProp, undefined);
41754175
});
41764176

4177-
it('handles overwriteDiscriminatorKey (gh-15040)', async function() {
4177+
it('handles overwriteDiscriminatorKey (gh-15218) (gh-15040)', async function() {
41784178
const dSchema1 = new mongoose.Schema({
41794179
field1: String
41804180
});
@@ -4202,7 +4202,7 @@ describe('Model', function() {
42024202
assert.equal(r1.field1, 'field1');
42034203
assert.equal(r1.key, type1Key);
42044204

4205-
const field2 = 'field2';
4205+
let field2 = 'field2';
42064206
await TestModel.bulkWrite([{
42074207
updateOne: {
42084208
filter: { _id: r1._id },
@@ -4214,7 +4214,13 @@ describe('Model', function() {
42144214
}
42154215
}]);
42164216

4217-
const r2 = await TestModel.findById(r1._id);
4217+
let r2 = await TestModel.findById(r1._id);
4218+
assert.equal(r2.key, type2Key);
4219+
assert.equal(r2.field2, field2);
4220+
4221+
field2 = 'field2 updated again';
4222+
await TestModel.updateOne({ _id: r1._id }, { $set: { key: type2Key, field2 } }, { overwriteDiscriminatorKey: true });
4223+
r2 = await TestModel.findById(r1._id);
42184224
assert.equal(r2.key, type2Key);
42194225
assert.equal(r2.field2, field2);
42204226
});

0 commit comments

Comments
 (0)