From 9856e4705927539ae5b8663f56ad28f772491e4c Mon Sep 17 00:00:00 2001 From: Shashank Kaul Date: Thu, 7 Sep 2023 21:35:41 +0530 Subject: [PATCH] feat: Safer types for `Model.distinct` and `Query.distinct`. --- test/types/queries.test.ts | 5 +++-- types/models.d.ts | 7 +++++-- types/query.d.ts | 6 +++--- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/test/types/queries.test.ts b/test/types/queries.test.ts index efca12618a5..2b6175dfd30 100644 --- a/test/types/queries.test.ts +++ b/test/types/queries.test.ts @@ -295,8 +295,9 @@ async function gh11306(): Promise { // 3. Create a Model. const MyModel = model('User', schema); - expectType(await MyModel.distinct('name')); - expectType(await MyModel.distinct('name')); + expectType(await MyModel.distinct('notThereInSchema')); + expectType(await MyModel.distinct('name')); + expectType(await MyModel.distinct<'overrideTest', number>('overrideTest')); } function autoTypedQuery() { diff --git a/types/models.d.ts b/types/models.d.ts index 2b0a5989445..1d001640565 100644 --- a/types/models.d.ts +++ b/types/models.d.ts @@ -443,8 +443,11 @@ declare module 'mongoose' { translateAliases(raw: any): any; /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */ - distinct(field: string, filter?: FilterQuery): QueryWithHelpers< - Array, + distinct( + field: DocKey, + filter?: FilterQuery + ): QueryWithHelpers< + Array, THydratedDocumentType, TQueryHelpers, TRawDocType, diff --git a/types/query.d.ts b/types/query.d.ts index 3963481a20b..2fb346fdd5c 100644 --- a/types/query.d.ts +++ b/types/query.d.ts @@ -317,10 +317,10 @@ declare module 'mongoose' { deleteOne(): QueryWithHelpers; /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */ - distinct( - field: string, + distinct( + field: DocKey, filter?: FilterQuery - ): QueryWithHelpers, DocType, THelpers, RawDocType, 'distinct'>; + ): QueryWithHelpers, DocType, THelpers, RawDocType, 'distinct'>; /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */ elemMatch(path: K, val: any): this;