Skip to content

Document.toObject() does not apply to subdocuments #14589

@AymericBebert

Description

@AymericBebert

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

Node.js version

20.12.2

MongoDB server version

7.0.2

Typescript version (if applicable)

5.4.5

Description

When calling myDocument.toObject with options, for example to remove the _id, the options do not seem to apply to subdocuments.

The documentation specifies (https://mongoosejs.com/docs/api/document.html#Document.prototype.toObject())

function deleteId(doc, ret, options) {
  delete ret._id;
  return ret;
}

const schema = mongoose.Schema({ name: String, docArr: [{ name: String }] });
const TestModel = mongoose.model('Test', schema);

const doc = new TestModel({ name: 'test', docArr: [{ name: 'test' }] });

// pass the transform as an inline option. Deletes `_id` property
// from both the top-level document and the subdocument.
const obj = doc.toObject({ transform: deleteId });
obj._id; // undefined
obj.docArr[0]._id; // undefined

It worked with 8.3.3 and seems broken in 8.3.4

Steps to Reproduce

it('subDocument toObject', () => {
    function deleteId(doc: any, ret: any, options: any) {
        delete ret._id;
        return ret;
    }

    const schema = new mongoose.Schema({name: String, docArr: [{name: String}]});
    const TestModel = mongoose.model('Test', schema);

    const doc = new TestModel({name: 'test', docArr: [{name: 'test'}]});

    // pass the transform as an inline option. Deletes `_id` property
    // from both the top-level document and the subdocument.
    const obj = doc.toObject({transform: deleteId});
    expect(obj._id).toEqual(undefined);
    expect(obj.docArr[0]._id).toEqual(undefined);
});

The test fails in 8.3.4 with

Expected: undefined
Received: "6641e1fe609d9d566a8bc095"

Expected Behavior

Any transform function specified in toObject options also propagates to any subdocuments.

Thanks

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

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions