Skip to content

Commit

Permalink
Merge pull request #13621 from Automattic/IslandRhythms/4628
Browse files Browse the repository at this point in the history
throw error after all saves are done
  • Loading branch information
vkarpov15 committed Jul 19, 2023
2 parents fffa85d + 6254c9c commit 2798cfd
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
24 changes: 17 additions & 7 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2850,24 +2850,34 @@ Model.create = async function create(doc, options) {
}
return res;
} else {
let firstError = null;
res = await Promise.all(args.map(async doc => {
const Model = this.discriminators && doc[discriminatorKey] != null ?
this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
this;
if (Model == null) {
throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
`found for model "${this.modelName}"`);
`found for model "${this.modelName}"`);
}
let toSave = doc;
try {
let toSave = doc;

if (!(toSave instanceof Model)) {
toSave = new Model(toSave);
}
if (!(toSave instanceof Model)) {
toSave = new Model(toSave);
}

await toSave.$save(options);
await toSave.$save(options);

return toSave;
return toSave;
} catch (err) {
if (!firstError) {
firstError = err;
}
}
}));
if (firstError) {
throw firstError;
}
}


Expand Down
14 changes: 14 additions & 0 deletions test/model.create.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,20 @@ describe('model', function() {
const docs = await Test.find();
assert.equal(docs.length, 5);
});
it('should throw an error only after all the documents have finished saving gh-4628', async function() {
const testSchema = new Schema({ name: { type: String, unique: true } });


const Test = db.model('gh4628Test', testSchema);
await Test.init();
const data = [];
for (let i = 0; i < 11; i++) {
data.push({ name: 'Test' + Math.abs(i - 4) });
}
await Test.create(data, { ordered: false }).catch(err => err);
const docs = await Test.find();
assert.equal(docs.length, 7); // docs 1,2,3,4 should not go through 11-4 == 7
});
});
});
});

0 comments on commit 2798cfd

Please sign in to comment.