-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Closed
Labels
confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.We've confirmed this is a bug in Mongoose and will fix it.
Milestone
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
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
- Define a Mongoose model with required field validations.
- Use
bulkWrite
to insert multiple documents where all documents violate the validation rules. - Observe that no error is thrown, and a default success response is returned.
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() {
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);
}
}
mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => testBulkWrite())
.catch(err => console.error('Error connecting to MongoDB:', err));
Result:
Bulk write result: {
result: {
ok: 1,
writeErrors: [],
writeConcernErrors: [],
insertedIds: [],
nInserted: 0,
nUpserted: 0,
nMatched: 0,
nModified: 0,
nRemoved: 0,
upserted: []
},
insertedCount: 0,
matchedCount: 0,
modifiedCount: 0,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: {},
n: 0
}
Expected Behavior
bulkWrite
should return an error or a response indicating that no documents were inserted due to validation failures.
Metadata
Metadata
Assignees
Labels
confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.We've confirmed this is a bug in Mongoose and will fix it.