Skip to content

bulkWrite does not throw an error if all documents are invalid (ordered: false) #14572

@AlexBrohshtut

Description

@AlexBrohshtut

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

  1. Define a Mongoose model with required field validations.
  2. Use bulkWrite to insert multiple documents where all documents violate the validation rules.
  3. 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

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions