Skip to content

[Bug] Validation silently passes for nested Map subdocuments loaded via init() #15957

@AbdelrahmanHafez

Description

@AbdelrahmanHafez

Prerequisites

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

Mongoose version

9.1.3

Node.js version

22.x

MongoDB server version

N/A

Typescript version (if applicable)

N/A

Description

re #15678 #15682

When a document with nested Maps (Map of subdocuments containing another Map) is loaded from the database via init(), validation silently passes for invalid data.

Steps to Reproduce

const mongoose = require('mongoose');

const employeeSchema = new mongoose.Schema({
  name: { type: String, required: true, minlength: 2 }
});

const teamSchema = new mongoose.Schema({
  employees: { type: Map, of: employeeSchema }
});

const companySchema = new mongoose.Schema({
  teams: { type: Map, of: teamSchema }
});

const Company = mongoose.model('Company', companySchema);

// Simulate loading from database via init()
const company = new Company();
company.init({
  _id: new mongoose.Types.ObjectId(),
  teams: {
    engineering: {
      employees: {
        john: { name: 'X' }  // Invalid: minlength is 2, 'X' has length 1
      }
    }
  }
});

// Validation should fail but passes silently
company.validate()
  .then(() => console.log('Validation passed (BUG - should have failed)'))
  .catch(err => console.log('Validation failed:', err.message));

Comparison with constructor (works correctly):

const company2 = new Company({
  teams: {
    engineering: {
      employees: {
        john: { name: 'X' }
      }
    }
  }
});

company2.validate()
  .then(() => console.log('Validation passed'))
  .catch(err => console.log('Validation failed:', err.message));
// Correctly fails with minlength validation error

Expected Behavior

Validation should fail with a minlength error for the name field

Documents loaded from the database (via init()) should behave identically to documents created via the constructor.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions