Skip to content

Mongoose 8.x: Required array schema validation breaks in static validation #15164

@skrtheboss

Description

@skrtheboss

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.9.3

Node.js version

20.17.0

MongoDB server version

7.0.14

Typescript version (if applicable)

5.5.4

Description

When using a schema with a required array field, static validation using Model.validate() fails when the array is empty, even though instance validation using new Model().validate() passes.

Steps to Reproduce

Run the following code with any 8.x.x version and it will fail the static validation:

const mongoose = require('mongoose');

async function runValidationTest() {
    const barSchema = new mongoose.Schema({
        foo: {
            type: mongoose.Schema.Types.String,
            required: true,
        },
    });

    const fooSchema = new mongoose.Schema({
        bars: {
            type: [barSchema],
            required: true,
        },
    });

    const Model = mongoose.model('FooTest', fooSchema);

    const fooInstance = {
        bars: [],
    };

    console.log('--- Instance Validation (new Model().validate()) ---');
    try {
        await new Model(fooInstance).validate();
        console.log('Instance validation: PASSED ✓');
    } catch (error) {
        console.error('Instance validation: FAILED ✗', error);
    }

    console.log('\n--- Static Validation (Model.validate()) ---');
    try {
        await Model.validate(fooInstance);
        console.log('Static validation: PASSED ✓');
    } catch (error) {
        console.error('Static validation: FAILED ✗', error);
    }
}

// Run the test
runValidationTest().catch(console.error);

Expected Behavior

Both instance validation (new Model().validate()) and static validation (Model.validate()) should pass when the bars array is empty because the array exists and satisfies the required constraint.

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