diff --git a/lib/model.js b/lib/model.js index 8021a4f622e..7596817bc1a 100644 --- a/lib/model.js +++ b/lib/model.js @@ -3427,6 +3427,7 @@ Model.$__insertMany = function(arr, options, callback) { const validationErrors = []; const validationErrorsToOriginalOrder = new Map(); + const results = ordered ? null : new Array(arr.length); const toExecute = arr.map((doc, index) => callback => { if (!(doc instanceof _this)) { @@ -3454,6 +3455,7 @@ Model.$__insertMany = function(arr, options, callback) { if (ordered === false) { validationErrors.push(error); validationErrorsToOriginalOrder.set(error, index); + results[index] = error; return callback(null, null); } return callback(error); @@ -3536,6 +3538,19 @@ Model.$__insertMany = function(arr, options, callback) { ...error.writeErrors[i], index: validDocIndexToOriginalIndex.get(error.writeErrors[i].index) }; + if (!ordered) { + results[validDocIndexToOriginalIndex.get(error.writeErrors[i].index)] = error.writeErrors[i]; + } + } + + if (!ordered) { + for (let i = 0; i < results.length; ++i) { + if (results[i] === void 0) { + results[i] = docAttributes[i]; + } + } + + error.results = results; } let firstErroredIndex = -1; @@ -3563,7 +3578,8 @@ Model.$__insertMany = function(arr, options, callback) { if (rawResult && ordered === false) { error.mongoose = { - validationErrors: validationErrors + validationErrors: validationErrors, + results: results }; } diff --git a/test/model.test.js b/test/model.test.js index e474e0f1850..745ef793baf 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -4570,6 +4570,11 @@ describe('Model', function() { const error = await Movie.insertMany(arr, { ordered: false }).then(() => null, err => err); assert.equal(error.message.indexOf('E11000'), 0); + assert.equal(error.results.length, 3); + assert.equal(error.results[0].name, 'Star Wars'); + assert.ok(error.results[1].err); + assert.ok(error.results[1].err.errmsg.includes('E11000')); + assert.equal(error.results[2].name, 'The Empire Strikes Back'); const docs = await Movie.find({}).sort({ name: 1 }).exec(); assert.equal(docs.length, 2); @@ -4677,6 +4682,11 @@ describe('Model', function() { assert.equal(err.insertedDocs[0].code, 'test'); assert.equal(err.insertedDocs[1].code, 'HARD'); + assert.equal(err.results.length, 3); + assert.ok(err.results[0].err.errmsg.includes('E11000')); + assert.equal(err.results[1].code, 'test'); + assert.equal(err.results[2].code, 'HARD'); + await Question.deleteMany({}); await Question.create({ code: 'MEDIUM', text: '123' }); await Question.create({ code: 'HARD', text: '123' });