Skip to content

Commit d8429aa

Browse files
authored
Merge pull request #13885 from Automattic/vkarpov15/gh-13799
fix(model): make `bulkSave()` persist changes that happen in pre('save') middleware
2 parents eee5ac1 + 9477860 commit d8429aa

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

lib/model.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -3565,11 +3565,9 @@ Model.bulkWrite = async function bulkWrite(ops, options) {
35653565
* @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option)
35663566
*
35673567
*/
3568-
Model.bulkSave = async function(documents, options) {
3568+
Model.bulkSave = async function bulkSave(documents, options) {
35693569
options = options || {};
35703570

3571-
const writeOperations = this.buildBulkWriteOperations(documents, { skipValidation: true, timestamps: options.timestamps });
3572-
35733571
if (options.timestamps != null) {
35743572
for (const document of documents) {
35753573
document.$__.saveOptions = document.$__.saveOptions || {};
@@ -3586,6 +3584,8 @@ Model.bulkSave = async function(documents, options) {
35863584

35873585
await Promise.all(documents.map(buildPreSavePromise));
35883586

3587+
const writeOperations = this.buildBulkWriteOperations(documents, { skipValidation: true, timestamps: options.timestamps });
3588+
35893589
const { bulkWriteResult, bulkWriteError } = await this.bulkWrite(writeOperations, options).then(
35903590
(res) => ({ bulkWriteResult: res, bulkWriteError: null }),
35913591
(err) => ({ bulkWriteResult: null, bulkWriteError: err })

test/document.test.js

+22
Original file line numberDiff line numberDiff line change
@@ -12479,6 +12479,28 @@ describe('document', function() {
1247912479
assert.ok(doc);
1248012480
});
1248112481

12482+
it('bulkSave() picks up changes in pre("save") middleware (gh-13799)', async() => {
12483+
const schema = new Schema({ name: String, _age: { type: Number, min: 0, default: 0 } });
12484+
schema.pre('save', function() {
12485+
this._age = this._age + 1;
12486+
});
12487+
12488+
const Person = db.model('Person', schema, 'Persons');
12489+
const person = new Person({ name: 'Jean-Luc Picard', _age: 59 });
12490+
12491+
await Person.bulkSave([person]);
12492+
12493+
let updatedPerson = await Person.findById(person._id);
12494+
12495+
assert.equal(updatedPerson?._age, 60);
12496+
12497+
await Person.bulkSave([updatedPerson]);
12498+
12499+
updatedPerson = await Person.findById(person._id);
12500+
12501+
assert.equal(updatedPerson?._age, 61);
12502+
});
12503+
1248212504
it('handles default embedded discriminator values (gh-13835)', async function() {
1248312505
const childAbstractSchema = new Schema(
1248412506
{ kind: { type: Schema.Types.String, enum: ['concreteKind'], required: true, default: 'concreteKind' } },

0 commit comments

Comments
 (0)