Skip to content

Commit 53f27aa

Browse files
authored
Merge pull request #12125 from emiljanitzek/feature/model-schema-type
fix(types): map correct generics from model to schema
2 parents aabf3b2 + 179a488 commit 53f27aa

File tree

3 files changed

+44
-3
lines changed

3 files changed

+44
-3
lines changed

test/types/models.test.ts

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import {
77
model,
88
Types,
99
UpdateQuery,
10-
CallbackError
10+
CallbackError,
11+
HydratedDocument,
12+
Query
1113
} from 'mongoose';
1214
import { expectAssignable, expectError, expectType } from 'tsd';
1315
import { AutoTypedSchemaType, autoTypedSchema } from './schema.test';
@@ -374,6 +376,45 @@ function gh12059() {
374376
Animal.bulkSave([animal], {});
375377
}
376378

379+
function schemaInstanceMethodsAndQueryHelpers() {
380+
type UserModelQuery = Query<any, HydratedDocument<User>, UserQueryHelpers> & UserQueryHelpers;
381+
interface UserQueryHelpers {
382+
byName(this: UserModelQuery, name: string): this
383+
}
384+
interface User {
385+
name: string;
386+
}
387+
interface UserInstanceMethods {
388+
doSomething(this: HydratedDocument<User>): string;
389+
}
390+
interface UserStaticMethods {
391+
findByName(name: string): Promise<HydratedDocument<User>>;
392+
}
393+
type UserModel = Model<User, UserQueryHelpers, UserInstanceMethods> & UserStaticMethods;
394+
395+
const userSchema = new Schema<User, UserModel, UserInstanceMethods, UserQueryHelpers, any, UserStaticMethods>({
396+
name: String
397+
}, {
398+
statics: {
399+
findByName(name: string) {
400+
return model('User').findOne({ name }).orFail();
401+
}
402+
},
403+
methods: {
404+
doSomething() {
405+
return 'test';
406+
}
407+
},
408+
query: {
409+
byName(this: UserModelQuery, name: string) {
410+
return this.where({ name });
411+
}
412+
}
413+
});
414+
415+
const TestModel = model<User, UserModel, UserQueryHelpers>('User', userSchema);
416+
}
417+
377418
function gh12100() {
378419
const schema = new Schema();
379420

types/connection.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ declare module 'mongoose' {
144144
/** Defines or retrieves a model. */
145145
model<T, U, TQueryHelpers = {}>(
146146
name: string,
147-
schema?: Schema<T, U, TQueryHelpers>,
147+
schema?: Schema<T, any, any, TQueryHelpers, any, any>,
148148
collection?: string,
149149
options?: CompileModelOptions
150150
): U;

types/index.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ declare module 'mongoose' {
7575

7676
export function model<T, U, TQueryHelpers = {}>(
7777
name: string,
78-
schema?: Schema<T, any, TQueryHelpers>,
78+
schema?: Schema<T, any, any, TQueryHelpers, any, any>,
7979
collection?: string,
8080
options?: CompileModelOptions
8181
): U;

0 commit comments

Comments
 (0)