Skip to content

Getters not applied in 3-level nested subdoc with toObject({ getters: true, virtuals: false }) in 8.5 #14840

@vkarpov15

Description

@vkarpov15

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.5.x

Node.js version

20.10.0

MongoDB server version

5.0.7

Typescript version (if applicable)

N/A

Description

Consider the following script:

const mongoose = require('mongoose');
require('util').inspect.defaultOptions.depth = 10;

// Define nested schemas
const Level3Schema = new mongoose.Schema({
  property: {
    type: String,
    get: (value) => value ? value.toUpperCase() : value,
  }
});

const Level2Schema = new mongoose.Schema({ level3: Level3Schema });
const Level1Schema = new mongoose.Schema({ level2: Level2Schema });
const MainSchema = new mongoose.Schema({ level1: Level1Schema });
const MainModel = mongoose.model('Main', MainSchema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017/test');
  await MainModel.deleteMany({});

  const doc = await MainModel.create({
    level1: {
      level2: {
        level3: {
          property: 'testValue'
        }
      }
    }
  });

  // Fetch and convert the document to an object with getters applied
  const result = await MainModel.findById(doc._id);
  const objectWithGetters = result.toObject({ getters: true, virtuals: false });

  console.log('Original Document:', doc);
  console.log('Value', doc.level1.level2.level3.property);
  console.log('With Getters Applied:', objectWithGetters);

  await mongoose.connection.close();
}

run().catch(err => console.log(err));

In 8.4, the output would include property: 'TEST VALUE' uppercased. In 8.5, that no longer happens. See comments on #14728

Steps to Reproduce

See above

Expected Behavior

getters applied

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