Skip to content

Commit

Permalink
Merge pull request #13885 from Automattic/vkarpov15/gh-13799
Browse files Browse the repository at this point in the history
fix(model): make `bulkSave()` persist changes that happen in pre('save') middleware
  • Loading branch information
vkarpov15 authored Sep 25, 2023
2 parents eee5ac1 + 9477860 commit d8429aa
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -3565,11 +3565,9 @@ Model.bulkWrite = async function bulkWrite(ops, options) {
* @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option)
*
*/
Model.bulkSave = async function(documents, options) {
Model.bulkSave = async function bulkSave(documents, options) {
options = options || {};

const writeOperations = this.buildBulkWriteOperations(documents, { skipValidation: true, timestamps: options.timestamps });

if (options.timestamps != null) {
for (const document of documents) {
document.$__.saveOptions = document.$__.saveOptions || {};
Expand All @@ -3586,6 +3584,8 @@ Model.bulkSave = async function(documents, options) {

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

const writeOperations = this.buildBulkWriteOperations(documents, { skipValidation: true, timestamps: options.timestamps });

const { bulkWriteResult, bulkWriteError } = await this.bulkWrite(writeOperations, options).then(
(res) => ({ bulkWriteResult: res, bulkWriteError: null }),
(err) => ({ bulkWriteResult: null, bulkWriteError: err })
Expand Down
22 changes: 22 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12479,6 +12479,28 @@ describe('document', function() {
assert.ok(doc);
});

it('bulkSave() picks up changes in pre("save") middleware (gh-13799)', async() => {
const schema = new Schema({ name: String, _age: { type: Number, min: 0, default: 0 } });
schema.pre('save', function() {
this._age = this._age + 1;
});

const Person = db.model('Person', schema, 'Persons');
const person = new Person({ name: 'Jean-Luc Picard', _age: 59 });

await Person.bulkSave([person]);

let updatedPerson = await Person.findById(person._id);

assert.equal(updatedPerson?._age, 60);

await Person.bulkSave([updatedPerson]);

updatedPerson = await Person.findById(person._id);

assert.equal(updatedPerson?._age, 61);
});

it('handles default embedded discriminator values (gh-13835)', async function() {
const childAbstractSchema = new Schema(
{ kind: { type: Schema.Types.String, enum: ['concreteKind'], required: true, default: 'concreteKind' } },
Expand Down

0 comments on commit d8429aa

Please sign in to comment.