Skip to content

Commit

Permalink
fix: prevent bulk operations from being executed multiple times (#2658)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mbroadst authored Dec 4, 2020
1 parent e7a42bb commit bb883f7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/bulk/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1212,16 +1212,15 @@ export abstract class BulkOperationBase {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};

if (this.s.executed) {
return handleEarlyError(new MongoError('Batch cannot be re-executed'), callback);
}

const writeConcern = WriteConcern.fromOptions(options);
if (writeConcern) {
this.s.writeConcern = writeConcern;
}

if (this.s.executed) {
const executedError = new MongoError('batch cannot be re-executed');
return handleEarlyError(executedError, callback);
}

// If we have current batch
if (this.isOrdered) {
if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch);
Expand All @@ -1236,6 +1235,7 @@ export abstract class BulkOperationBase {
return handleEarlyError(emptyBatchError, callback);
}

this.s.executed = true;
return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]);
}

Expand Down
18 changes: 18 additions & 0 deletions test/functional/bulk.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1759,4 +1759,22 @@ describe('Bulk', function () {
});
})
);

it(
'should throw an error if bulk execute is called more than once',
withClientV2(function (client, done) {
const bulk = client.db().collection('coll').initializeUnorderedBulkOp();
bulk.insert({});

bulk.execute((err, result) => {
expect(err).to.not.exist;
expect(result).to.exist;

bulk.execute(err => {
expect(err).to.match(/Batch cannot be re-executed/);
done();
});
});
})
);
});

0 comments on commit bb883f7

Please sign in to comment.