fix(model): add results
property to unordered insertMany()
to make it easy to identify exactly which documents were inserted
#13163
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.
Fix #12791
Summary
#12791 pointed out that it is still very tricky to figure out exactly which documents were inserted if you're using
insertMany()
withordered: false
. That's because the document can either 1) fail Mongoose validation, 2) fail because of a MongoDB server error, 3) succeed. And the results for (1), (2), and (3) are all in separate properties, which means you need to do some stitching to figure out exactly what happened with a particular document.With this PR, if there were any errors, there will be a
results
property on the error (orres.mongoose.results
if you're usingrawResult: true
) that contains an array which has either 1) the document if the document was successfully inserted, 2) the MongoDB write error if the write failed, 3) the Mongoose validation error if the document failed validation. The index in theresults
array corresponds to the index of the original document inarr
in theModel.insertMany(arr)
call, so this should make it easy to determine if an individual document succeeded or not ininsertMany()
. Just checkerror.results[i] instanceof mongoose.Document
.Examples