-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Open
Labels
typescriptTypes or Types-test related issue / Pull RequestTypes or Types-test related issue / Pull Request
Milestone
Description
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()
:

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
Labels
typescriptTypes or Types-test related issue / Pull RequestTypes or Types-test related issue / Pull Request