Skip to content

Deduced type of an array in a schema is plain array instead of mongoose array. #14983

Open

Description

Prerequisites

  • I have written a descriptive issue title

Mongoose version

8.6.2

Node.js version

20.18.0

MongoDB version

7.0.14

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10.0.22631

Issue

Here is simple example of schema in mongoose:

const ExampleSchema = new Schema(
  {
    names: [
      {
        type: String,
      },
    ],
  },
  {
    methods: {
      addToNames: async function (name: string) {
        // this.updateOne() // accessible
        this.names.addToSet(name); // Property 'addToSet' does not exist on type 'string[]'. [2339]
      },
    },
  },
);

this object in a methods is a hydrated document, however array deduced not as mongoose array but as plain array instead. Example demonstrates this issue by trying to use addToSet method of a mongoose array, but getting type error.

Same issue can be depicted with this example:

type IExampleDocument = HydratedDocumentFromSchema<typeof ExampleSchema>;
const Example = model<IExampleDocument>("example", ExampleSchema);
const example = await Example.create({ names: ["hello"] });
example.names.addToSet("example"); // Property 'addToSet' does not exist on type 'string[]'. [2339]

I have pretty vague understanding of how schemas in typescript should be properly defined, I've read that we can provide interfaces ourselves by using template parameters of model and Schema however it essentially produces a duplication in a boilerplate types and defies already defined principles of deduction established with HydratedDocumentFromSchema, InferSchemaType and other typescript helper functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    helpThis issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessaryhelp wanted

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions