diff --git a/lib/model.js b/lib/model.js index 901228e2120..73d38045073 100644 --- a/lib/model.js +++ b/lib/model.js @@ -3381,10 +3381,19 @@ Model.$__insertMany = function(arr, options, callback) { _this.collection.insertMany(docObjects, options, function(error, res) { if (error) { + // `writeErrors` is a property reported by the MongoDB driver, + // just not if there's only 1 error. if (error.writeErrors == null && get(error, 'result.result.writeErrors') != null) { error.writeErrors = error.result.result.writeErrors; } + + // `insertedDocs` is a Mongoose-specific property + const erroredIndexes = new Set(error.writeErrors.map(err => err.index)); + error.insertedDocs = docAttributes.filter((doc, i) => { + return !erroredIndexes.has(i); + }); + callback(error, null); return; } diff --git a/test/model.test.js b/test/model.test.js index 56081f17db3..3c59e5afb73 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -4548,6 +4548,9 @@ describe('Model', function() { let err = yield Question.insertMany(data, opts).catch(err => err); assert.ok(Array.isArray(err.writeErrors)); assert.equal(err.writeErrors.length, 1); + assert.equal(err.insertedDocs.length, 2); + assert.equal(err.insertedDocs[0].code, 'test'); + assert.equal(err.insertedDocs[1].code, 'HARD'); yield Question.deleteMany({}); yield Question.create({ code: 'MEDIUM', text: '123' }); @@ -4556,6 +4559,8 @@ describe('Model', function() { err = yield Question.insertMany(data, opts).catch(err => err); assert.ok(Array.isArray(err.writeErrors)); assert.equal(err.writeErrors.length, 2); + assert.equal(err.insertedDocs.length, 1); + assert.equal(err.insertedDocs[0].code, 'test'); }); });