Skip to content

Commit

Permalink
fix(types): map correct generics from model to schema
Browse files Browse the repository at this point in the history
  • Loading branch information
emiljanitzek committed Jul 22, 2022
1 parent bc302f4 commit dd0dd96
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
35 changes: 34 additions & 1 deletion test/types/models.test.ts
Expand Up @@ -7,7 +7,9 @@ import {
model,
Types,
UpdateQuery,
CallbackError
CallbackError,
HydratedDocument,
Query
} from 'mongoose';
import { expectAssignable, expectError, expectType } from 'tsd';
import { AutoTypedSchemaType, autoTypedSchema } from './schema.test';
Expand Down Expand Up @@ -329,6 +331,37 @@ function gh11911() {
});
}

function schemaInstanceMethodsAndQueryHelpers() {
type UserModelQuery = Query<any, HydratedDocument<User>, UserQueryHelpers> & UserQueryHelpers;
interface UserQueryHelpers {
byName(this: UserModelQuery, name: string): this
}
interface User {
name: string;
}
interface UserInstanceMethods {
findByName(name: string): Promise<HydratedDocument<User>>;
}
type UserModel = Model<User, UserQueryHelpers> & UserInstanceMethods;

const userSchema = new Schema<User, UserModel, UserInstanceMethods, UserQueryHelpers>({
name: String
}, {
methods: {
findByName(name: string) {
return model('User').findOne({ name }).orFail();
}
},
query: {
byName(this: UserModelQuery, name: string) {
return this.where({ name });
}
}
});

const TestModel = model<User, UserModel, UserQueryHelpers>('User', userSchema);
}

function gh12100() {
const schema = new Schema();

Expand Down
2 changes: 1 addition & 1 deletion types/connection.d.ts
Expand Up @@ -144,7 +144,7 @@ declare module 'mongoose' {
/** Defines or retrieves a model. */
model<T, U, TQueryHelpers = {}>(
name: string,
schema?: Schema<T, U, TQueryHelpers>,
schema?: Schema<T, U, any, TQueryHelpers, any, any>,
collection?: string,
options?: CompileModelOptions
): U;
Expand Down
2 changes: 1 addition & 1 deletion types/index.d.ts
Expand Up @@ -74,7 +74,7 @@ declare module 'mongoose' {

export function model<T, U, TQueryHelpers = {}>(
name: string,
schema?: Schema<T, any, TQueryHelpers>,
schema?: Schema<T, U, any, TQueryHelpers, any, any>,
collection?: string,
options?: CompileModelOptions
): U;
Expand Down

0 comments on commit dd0dd96

Please sign in to comment.