Skip to content

[Bug] Unsafe prototype getter generated for ALL nested paths (breaks Jest/Introspection) #15961

@jml6m

Description

@jml6m

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

Node.js version

22.17.1

MongoDB server version

6.21.0

Typescript version (if applicable)

No response

Description

In Mongoose 9.x, defining any nested path in a Schema generates a getter on Model.prototype that is unsafe for static introspection.

When tools like Jest (specifically jest.mock or automock) inspect the Model class, they traverse the prototype chain. The generated getter attempts to access this.$__.getters. However, when accessing the property directly on the prototype (e.g., Model.prototype.myField), this refers to the Prototype object, not a Document instance. Consequently, this.$__ is undefined, causing a crash.

Steps to Reproduce

Run the following standalone script (no external dependencies required):

const mongoose = require('mongoose');

// 1. Define ANY schema with a nested path
const schema = new mongoose.Schema({
  randomWord: { nested: String }
});

const Model = mongoose.model('Test', schema);

console.log('Checking prototype...');

try {
  // 2. Accessing the property on the prototype triggers the crash.
  // This simulates what `jest.mock` does when inspecting modules.
  const val = Model.prototype.randomWord;
} catch (err) {
  console.error('CRASH REPRODUCED:');
  console.error(err.message); 
  console.error(err.stack);
}

Actual Output

CRASH REPRODUCED:
Cannot read properties of undefined (reading 'getters')
TypeError: Cannot read properties of undefined (reading 'getters')
    at Model.get [as randomWord] (node_modules/mongoose/lib/helpers/document/compile.js:80:23)

Expected Behavior

Additional Context
This breaks generic unit tests that rely on jest.mock('./my.model.js'), as Jest iterates over exports and touches their prototype properties, triggering this crash immediately upon test suite load.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions