Skip to content

If I explicitly set the type of a PopulatedDoc variable using populate in a query, the virtual variables of the retrieved instances become nonexistent #15111

@nikzanda

Description

@nikzanda

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

Node.js version

20.10.0

MongoDB server version

6.0.2

Typescript version (if applicable)

5.5.4

Description

It seems there is a typing conflict when executing a query using populate and explicitly setting the type of the PopulatedDoc variable. It's likely that the virtual variables are being overwritten.

As you can see from the example, in the query I explicitly declare the type of the PopulatedDoc variable "child". After that, if I try to add one of the retrieved instances to an array of type ParentInstance, I get a typing error. The same virtual variables no longer exist, and the linter returns an error.

const filteredParents: ParentInstance[] = [];
const parents = await Parent.find().populate<{ child: ChildInstance }>(
  'child'
);
parents.forEach((parent) => {
  const condition = parent.fullName === 'fake condition'; // error
  if (condition) {
    filteredParents.push(parent); // error
  }
});

The full error:

Argument of type 'Document<unknown, {}, MergeType<IParent, { child: Document<unknown, {}, IChild> & Omit<IChild & Required<{ _id: ObjectId; }> & { __v: number; }, "id"> & IChildVirtuals; }>> & Omit<...> & { ...; } & Required<...> & { ...; }' is not assignable to parameter of type 'Document<unknown, {}, IParent> & Omit<IParent & Required<{ _id: ObjectId; }> & { __v: number; }, keyof IParentVirtuals> & IParentVirtuals'.
  Property 'fullName' is missing in type 'Document<unknown, {}, MergeType<IParent, { child: Document<unknown, {}, IChild> & Omit<IChild & Required<{ _id: ObjectId; }> & { __v: number; }, "id"> & IChildVirtuals; }>> & Omit<...> & { ...; } & Required<...> & { ...; }' but required in type 'IParentVirtuals'.(2345)
index.ts(64, 3): 'fullName' is declared here.

ParentInstance is declared like this:

type ParentInstance = HydratedDocument<
  IParent,
  ParentDocumentOverrides & IParentVirtuals
>;

If I remove & IParentVirtuals from the declaration, the error disappears.

Steps to Reproduce

Reproduction link here.

Expected Behavior

If I explicitly set the type of a PopulatedDoc variable, I should still be able to use the virtual variables of the retrieved instances.

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.typescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions