Skip to content

Commit

Permalink
Merge pull request #12125 from emiljanitzek/feature/model-schema-type
Browse files Browse the repository at this point in the history
fix(types): map correct generics from model to schema
  • Loading branch information
vkarpov15 committed Aug 3, 2022
2 parents aabf3b2 + 179a488 commit 53f27aa
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
43 changes: 42 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 @@ -374,6 +376,45 @@ function gh12059() {
Animal.bulkSave([animal], {});
}

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

const userSchema = new Schema<User, UserModel, UserInstanceMethods, UserQueryHelpers, any, UserStaticMethods>({
name: String
}, {
statics: {
findByName(name: string) {
return model('User').findOne({ name }).orFail();
}
},
methods: {
doSomething() {
return 'test';
}
},
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, any, any, TQueryHelpers, any, any>,
collection?: string,
options?: CompileModelOptions
): U;
Expand Down
2 changes: 1 addition & 1 deletion types/index.d.ts
Expand Up @@ -75,7 +75,7 @@ declare module 'mongoose' {

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

0 comments on commit 53f27aa

Please sign in to comment.