Automattic / Automattic/mongoose
Document method types are missing methods when queried from statics
- Dominant language
- JavaScript
- Stars
- 27.5k
- Forks
- 4k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 35
Description
### Prerequisites
- [x] I have written a descriptive issue title
- [x] 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](https://mongoosejs.com/docs/typescript/statics-and-methods.html)):
```ts
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()`:
### 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.
Contributor guide
Research direction
Start with the reported TypeScript reproduction, focusing on the schema's methods and statics entry points and the findOne().orFail() query path. Confirm that a query returned from findByName preserves the updateName method type, then add a regression test covering the static-query case and verify the existing direct-query behavior remains correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- node.js, typescript
- Domain
- backend, databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100