Skip to content

toObject does not keep populated types #16085

@skrukwa

Description

@skrukwa

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

Node.js version

24.13.1

MongoDB server version

n/a

Typescript version (if applicable)

5.8.3

Description

calling toObject after populate does not keep the populated type in the plain object type

Steps to Reproduce

const childSchema = new Schema({
    name: String
});
const Child = mongoose.model('Child', childSchema);

const parentSchema = new Schema({
    title: String,
    children: [{ type: Schema.Types.ObjectId, ref: 'Child' }]
});
const Parent = mongoose.model('Parent', parentSchema);

async function reproduce() {
    const parentDoc = new Parent({ title: 'My Parent', children: [] });

    const populatedDoc = await parentDoc.populate<{
        children: Types.DocumentArray<HydratedDocFromModel<typeof Child>>;
    }>('children');

    const childNameFromHydrated = populatedDoc.children[0]?.name; // OK

    const plainObject = populatedDoc.toObject();
    const childNameFromPlain = plainObject.children[0].name; // Property 'name' does not exist on type 'ObjectId'. ts(2339)
}

Expected Behavior

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    typescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions