diff --git a/lib/bulk/common.js b/lib/bulk/common.js index 894d8569c2..fea6c18e34 100644 --- a/lib/bulk/common.js +++ b/lib/bulk/common.js @@ -475,7 +475,7 @@ function mergeBatchResults(batch, bulkResult, err, result) { if (Array.isArray(result.writeErrors)) { for (let i = 0; i < result.writeErrors.length; i++) { const writeError = { - index: batch.originalIndexes[i], + index: batch.originalIndexes[result.writeErrors[i].index], code: result.writeErrors[i].code, errmsg: result.writeErrors[i].errmsg, op: batch.operations[result.writeErrors[i].index] diff --git a/test/functional/bulk.test.js b/test/functional/bulk.test.js index 434f48d40b..ff13afa832 100644 --- a/test/functional/bulk.test.js +++ b/test/functional/bulk.test.js @@ -1660,4 +1660,41 @@ describe('Bulk', function() { ); }); }); + + it('should preserve order of operation index in unordered bulk operation', function() { + const client = this.configuration.newClient(); + return client.connect().then(() => { + this.defer(() => client.close()); + + const coll = client.db().collection('bulk_op_ordering_test'); + function ignoreNsNotFound(err) { + if (!err.message.match(/ns not found/)) throw err; + } + + return coll + .drop() + .catch(ignoreNsNotFound) + .then(() => { + const batch = coll.initializeUnorderedBulkOp(); + batch.insert({ _id: 1, a: 0 }); + batch.insert({ _id: 1, a: 0 }); + batch.insert({ _id: 2, a: 0 }); + batch.insert({ _id: 2, a: 0 }); + return batch.execute(); + }) + .then( + () => { + throw new Error('expected a bulk error'); + }, + err => { + expect(err) + .to.have.property('writeErrors') + .with.length(2); + + expect(err).to.have.nested.property('writeErrors[0].err.index', 1); + expect(err).to.have.nested.property('writeErrors[1].err.index', 3); + } + ); + }); + }); });