Skip to content

Commit 71e6ad4

Browse files
committed
fix(model): make bulkSave() save changes in discriminator paths if calling bulkSave() on base model
Fix #13907
1 parent b721f54 commit 71e6ad4

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

lib/model.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3780,6 +3780,7 @@ Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, op
37803780
}
37813781

37823782
setDefaultOptions();
3783+
const discriminatorKey = this.schema.options.discriminatorKey;
37833784

37843785
const writeOperations = documents.reduce((accumulator, document, i) => {
37853786
if (!options.skipValidation) {
@@ -3810,6 +3811,12 @@ Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, op
38103811

38113812
_applyCustomWhere(document, where);
38123813

3814+
// Set the discriminator key, so bulk write casting knows which
3815+
// schema to use re: gh-13907
3816+
if (document[discriminatorKey] != null && !(discriminatorKey in where)) {
3817+
where[discriminatorKey] = document[discriminatorKey];
3818+
}
3819+
38133820
document.$__version(where, delta);
38143821
const writeOperation = { updateOne: { filter: where, update: changes } };
38153822
utils.injectTimestampsOption(writeOperation.updateOne, options.timestamps);

test/model.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6239,6 +6239,27 @@ describe('Model', function() {
62396239
assert.equal(writeOperations.length, 3);
62406240
});
62416241

6242+
it('saves changes in discriminators if calling `bulkSave()` on base model (gh-13907)', async() => {
6243+
const schema = new mongoose.Schema(
6244+
{ value: String },
6245+
{ discriminatorKey: 'type' }
6246+
);
6247+
const typeASchema = new mongoose.Schema({ aValue: String });
6248+
schema.discriminator('A', typeASchema);
6249+
6250+
const TestModel = db.model('Test', schema);
6251+
const testData = { value: 'initValue', type: 'A', aValue: 'initAValue' };
6252+
const doc = await TestModel.create(testData);
6253+
6254+
doc.value = 'updatedValue1';
6255+
doc.aValue = 'updatedValue2';
6256+
await TestModel.bulkSave([doc]);
6257+
6258+
const findDoc = await TestModel.findById(doc._id);
6259+
assert.strictEqual(findDoc.value, 'updatedValue1');
6260+
assert.strictEqual(findDoc.aValue, 'updatedValue2');
6261+
});
6262+
62426263
it('accepts `timestamps: false` (gh-12059)', async() => {
62436264
// Arrange
62446265
const userSchema = new Schema({

0 commit comments

Comments
 (0)