Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

throw error after all saves are done #13621

Merged
merged 3 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 17 additions & 7 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2878,24 +2878,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
});
});
});
});