Skip to content

Commit

Permalink
fix(model): make bulkSave() save changes in discriminator paths if ca…
Browse files Browse the repository at this point in the history
…lling bulkSave() on base model

Fix #13907
  • Loading branch information
vkarpov15 committed Oct 9, 2023
1 parent b721f54 commit 71e6ad4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -3780,6 +3780,7 @@ Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, op
}

setDefaultOptions();
const discriminatorKey = this.schema.options.discriminatorKey;

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

_applyCustomWhere(document, where);

// Set the discriminator key, so bulk write casting knows which
// schema to use re: gh-13907
if (document[discriminatorKey] != null && !(discriminatorKey in where)) {
where[discriminatorKey] = document[discriminatorKey];
}

document.$__version(where, delta);
const writeOperation = { updateOne: { filter: where, update: changes } };
utils.injectTimestampsOption(writeOperation.updateOne, options.timestamps);
Expand Down
21 changes: 21 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6239,6 +6239,27 @@ describe('Model', function() {
assert.equal(writeOperations.length, 3);
});

it('saves changes in discriminators if calling `bulkSave()` on base model (gh-13907)', async() => {
const schema = new mongoose.Schema(
{ value: String },
{ discriminatorKey: 'type' }
);
const typeASchema = new mongoose.Schema({ aValue: String });
schema.discriminator('A', typeASchema);

const TestModel = db.model('Test', schema);
const testData = { value: 'initValue', type: 'A', aValue: 'initAValue' };
const doc = await TestModel.create(testData);

doc.value = 'updatedValue1';
doc.aValue = 'updatedValue2';
await TestModel.bulkSave([doc]);

const findDoc = await TestModel.findById(doc._id);
assert.strictEqual(findDoc.value, 'updatedValue1');
assert.strictEqual(findDoc.aValue, 'updatedValue2');
});

it('accepts `timestamps: false` (gh-12059)', async() => {
// Arrange
const userSchema = new Schema({
Expand Down

0 comments on commit 71e6ad4

Please sign in to comment.