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

fix(model): add results property to unordered insertMany() to make it easy to identify exactly which documents were inserted #13163

Merged
merged 2 commits into from Mar 17, 2023

Conversation

vkarpov15
Copy link
Collaborator

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() with ordered: 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 (or res.mongoose.results if you're using rawResult: 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 the results array corresponds to the index of the original document in arr in the Model.insertMany(arr) call, so this should make it easy to determine if an individual document succeeded or not in insertMany(). Just check error.results[i] instanceof mongoose.Document.

Examples

…e it easy to identify exactly which documents were inserted

Fix #12791
Copy link
Collaborator

@hasezoey hasezoey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, but documentation and types are missing

@hasezoey hasezoey linked an issue Mar 13, 2023 that may be closed by this pull request
2 tasks
@vkarpov15
Copy link
Collaborator Author

@hasezoey take a look now, I added types and docs, and fixed some test issues

@vkarpov15 vkarpov15 merged commit b36e78b into 6.x Mar 17, 2023
51 checks passed
@vkarpov15 vkarpov15 deleted the vkarpov15/gh-12791-2 branch March 17, 2023 14:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Mongoose bulk insert misses critical information
2 participants