Skip to content

Commit

Permalink
fix(model): report insertedDocs on insertMany() errors
Browse files Browse the repository at this point in the history
Fix #8938
  • Loading branch information
vkarpov15 committed May 17, 2020
1 parent faaff44 commit b5c5211
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
5 changes: 5 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
Expand All @@ -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');
});
});

Expand Down

0 comments on commit b5c5211

Please sign in to comment.