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

feat(model): added throwOnValidationError option for bulkWrite and insertMany #13258

Closed
wants to merge 3 commits into from

Conversation

lpizzinidev
Copy link
Contributor

Summary
Added throwOnValidationError option for Model.bulkWrite and Model.insertMany (default to false).
If set to true and ordered: true the methods will throw an error if there were operations that failed validation, but all operations that passed validation succeeded.

Example

const createdUser = await User.create({ name: 'Test' });

// Will throw an error
await User.bulkWrite(
  [
    {
      updateOne: {
        filter: { _id: createdUser._id },
        update: { $set: { age: 'NaN' } },
        upsert: true,
      },
    },
    {
      updateOne: {
        filter: { _id: createdUser._id },
        update: { $set: { age: 13 } },
        upsert: true,
      },
    },
  ],
  { ordered: false, throwOnValidationError: true }
);

Notes
Let me know what could be a valid error message.
I commented out a test case that was causing the test script to fail.

Closes #13256

Copy link
Collaborator

@vkarpov15 vkarpov15 left a comment

Choose a reason for hiding this comment

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

LGTM so far, but error class needs to be implemented

@@ -3106,6 +3108,10 @@ Model.$__insertMany = function(arr, options, callback) {
_setIsNew(attribute, false);
}

if (ordered === false && throwOnValidationError && validationErrors.length > 0) {
return callback(new Error('throwOnValidationError'), null);
Copy link
Collaborator

Choose a reason for hiding this comment

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

A good start, but I think we need a new error class for this. Can you add a MongooseBulkWriteError class that contains response from server, validationErrors list of validation errors, and results array?

@vkarpov15
Copy link
Collaborator

Closing in favor of #13410

@vkarpov15 vkarpov15 closed this May 17, 2023
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.

throwOnValidationError for bulkWrite() and insertMany()
2 participants