Skip to content

Commit

Permalink
fix(model): add results property to unordered insertMany() to mak…
Browse files Browse the repository at this point in the history
…e it easy to identify exactly which documents were inserted

Fix #12791
  • Loading branch information
vkarpov15 committed Mar 13, 2023
1 parent 0b2f6ed commit 1111f98
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
18 changes: 17 additions & 1 deletion lib/model.js
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -3563,7 +3578,8 @@ Model.$__insertMany = function(arr, options, callback) {

if (rawResult && ordered === false) {
error.mongoose = {
validationErrors: validationErrors
validationErrors: validationErrors,
results: results
};
}

Expand Down
10 changes: 10 additions & 0 deletions test/model.test.js
Expand Up @@ -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);
Expand Down Expand Up @@ -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' });
Expand Down

0 comments on commit 1111f98

Please sign in to comment.