Skip to content

Commit bb883f7

Browse files
authored
fix: prevent bulk operations from being executed multiple times (#2658)
This spec compliant behavior was lost through refactoring in recent years. We now prevent users from calling execute multiple times on a bulk operation. NODE-2926
1 parent e7a42bb commit bb883f7

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

src/bulk/common.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -1212,16 +1212,15 @@ export abstract class BulkOperationBase {
12121212
if (typeof options === 'function') (callback = options), (options = {});
12131213
options = options || {};
12141214

1215+
if (this.s.executed) {
1216+
return handleEarlyError(new MongoError('Batch cannot be re-executed'), callback);
1217+
}
1218+
12151219
const writeConcern = WriteConcern.fromOptions(options);
12161220
if (writeConcern) {
12171221
this.s.writeConcern = writeConcern;
12181222
}
12191223

1220-
if (this.s.executed) {
1221-
const executedError = new MongoError('batch cannot be re-executed');
1222-
return handleEarlyError(executedError, callback);
1223-
}
1224-
12251224
// If we have current batch
12261225
if (this.isOrdered) {
12271226
if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch);
@@ -1236,6 +1235,7 @@ export abstract class BulkOperationBase {
12361235
return handleEarlyError(emptyBatchError, callback);
12371236
}
12381237

1238+
this.s.executed = true;
12391239
return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]);
12401240
}
12411241

test/functional/bulk.test.js

+18
Original file line numberDiff line numberDiff line change
@@ -1759,4 +1759,22 @@ describe('Bulk', function () {
17591759
});
17601760
})
17611761
);
1762+
1763+
it(
1764+
'should throw an error if bulk execute is called more than once',
1765+
withClientV2(function (client, done) {
1766+
const bulk = client.db().collection('coll').initializeUnorderedBulkOp();
1767+
bulk.insert({});
1768+
1769+
bulk.execute((err, result) => {
1770+
expect(err).to.not.exist;
1771+
expect(result).to.exist;
1772+
1773+
bulk.execute(err => {
1774+
expect(err).to.match(/Batch cannot be re-executed/);
1775+
done();
1776+
});
1777+
});
1778+
})
1779+
);
17621780
});

0 commit comments

Comments
 (0)