fix(model): ensure consistent ordering of validation errors in insertMany() with ordered: false and rawResult: true
#12866
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Re: #12791
Summary
#12791 points out a few issues with our error reporting with
create()andinsertMany(). We do have a workaround usinginsertMany(), but the workaround does have a potential flaw: currently,res.mongoose.validationErrorscan report validation errors in any order.Specifically, the validation errors are in the order that the errors occur, not in the order of the original documents passed in. So if
doc1anddoc2both fail validation,const res = await Model.insertMany([doc1, doc2], { ordered: false, rawResult: true })can end up with doc2's validation error before doc1's inres.mongoose.validationErrorsif doc1's validation takes longer than doc2's.With this change,
res.mongoose.validationErrorswill always be in the same order as the documents passed in. So doc1's validation error will always be before doc2's. So to check whether a document at indexiwas actually inserted, you need to check ifi in res.insertedIds. To check if there was a MongoDB-specific write error, check if!(i in res.insertedIds)Examples