Skip to content

Document method types are missing methods when queried from statics #15532

@domharrington

Description

@domharrington

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

Node.js version

20.19.0

MongoDB server version

7.0.15

Typescript version (if applicable)

5.8.3

Description

Typescript method types are getting dropped if they are returned from a query called from a static method.

Steps to Reproduce

I have the following code (heavily inspired by the docs):

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema(
  {
    name: { type: String, required: true },
  },
  {
    methods: {
      updateName(name: string) {
        this.name = name;
        return this.save();
      }
    },
    statics: {
      findByName(name: string) {
        return this.findOne({ name });
      }
    }
  }
);
const UserModel = mongoose.model('User', userSchema);

const doc = new UserModel({ name: 'test' });
// Compiles correctly
doc.updateName('foo');

const foundDoc = await UserModel.findOne({ name: 'test' }).orFail();
// Compiles correctly
foundDoc.updateName('foo');

const foundDocFromStatic = await UserModel.findByName('test').orFail();
// Method types are broken
foundDocFromStatic.updateName('foo');

The foundDoc variable has the updateName method typed correctly. The foundDocFromStatic variable seems to have lost the method typing information, even though findByName also just does a findOne():

Image

Expected Behavior

I would expect method types to be returned when the query is happening from a static.

Am I doing something wrong here? Thanks in advance.

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