-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
bulkWrite does not throw an error if all documents are invalid (ordered: false) #14572
Comments
Proposed Solution for Handling All Validation Failures in
|
const mongoose = require('mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({
name: { type: String, required: true }
});
const User = mongoose.model('User', userSchema);
async function testBulkWrite() {
await mongoose.connect('mongodb://localhost:27017');
await mongoose.connection.dropDatabase();
try {
const result = await User.bulkWrite([
{
insertOne: {
document: { name: '' } // This is invalid as `name` is required
}
},
{
insertOne: {
document: { name: '' } // This is also invalid
}
}
], { ordered: false } );
console.log('Bulk write result:', result);
} catch (error) {
console.error('Error during bulk write:', error);
}
}
testBulkWrite(); |
…lidationError` set and all ops invalid Fix #14572
Not throwing an error is expected behavior, you should opt in to throwing an error if any bulkWrite ops fail validation using const result = await User.bulkWrite([
{
insertOne: {
document: { name: '' } // This is invalid as `name` is required
}
},
{
insertOne: {
document: { name: '' } // This is also invalid
}
}
], { ordered: false, throwOnValidationError: true } ); There's a bug where we don't throw an error if all operations fail validation even if |
Good, it seems like it does the job 👍🏻 |
fix(model): make `bulkWrite()` and `insertMany()` throw if `throwOnValidationError` set and all ops invalid
feat(model): add throwOnValidationError option for opting into getting MongooseBulkWriteError if all valid operations succeed in bulkWrite() and insertMany()
Prerequisites
Mongoose version
6.12.2
Node.js version
20.9.0
MongoDB server version
5.0
Typescript version (if applicable)
No response
Description
When using
bulkWrite
in Mongoose to insert multiple documents, if all documents fail validation (e.g., required fields missing),bulkWrite
completes without throwing any errors. Instead, it returns a default result indicating success, which is misleading as no documents are written to the database due to validation errors.It seems that the change that was expecting to fix the error on empty array insertion may be involved: 17c31b7
Steps to Reproduce
bulkWrite
to insert multiple documents where all documents violate the validation rules.Result:
Expected Behavior
bulkWrite
should return an error or a response indicating that no documents were inserted due to validation failures.The text was updated successfully, but these errors were encountered: