Skip to content

Document.prototype.validate() does not validate subdocument required fields with validateModifiedOnly option #14677

Closed
@lcrosetto

Description

@lcrosetto

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.4.3

Node.js version

20.14.0

MongoDB server version

7.0.11

Typescript version (if applicable)

No response

Description

In versions 8.2.4 and prior, a call to Document.prototype.validate(null, {validateModifiedOnly: true}) would throw an error if required fields in a subdocument were missing. In 8.3.0 and subsequent versions, validate() no longer checks for required fields in subdocuments if the validateModifiedOnly option is set to true.

If subdocuments are added, the required fields should be validated as was done in 8.2.4 and prior.

Steps to Reproduce

The following code will throw an error in mongoose versions 8.2.4 and prior, and succeed in 8.3.0 and subsequent:

      const embedSchema = new mongoose.Schema({
        field1: {
          type: String,
          required: true,
        },
        field2: String,
      });
      const testSchema = new mongoose.Schema({
        testField: {
          type: String,
          required: true,
        },
        testArray: [embedSchema],
      });
      const TestModel = mongoose.model('Test', testSchema);
      const m = new TestModel({testArray: [{field2: 'test'}]});
      await m.validate(null, {validateModifiedOnly: true});

With the validateModifiedOnly option, testField is not required, however it also skips the check for field1 in the subdocument (which is missing) starting in version 8.3.0.

Expected Behavior

If a subdocument is added, validate() should check that all required fields are present when the validateModifiedOnly is set to true.

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