Skip to content

Commit

Permalink
BREAKING CHANGE: Safer types for Model.distinct and Query.distinct.
Browse files Browse the repository at this point in the history
  • Loading branch information
kaulsh committed Sep 7, 2023
1 parent f6511c0 commit b951883
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
5 changes: 3 additions & 2 deletions test/types/queries.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,9 @@ async function gh11306(): Promise<void> {
// 3. Create a Model.
const MyModel = model<User>('User', schema);

expectType<any[]>(await MyModel.distinct('name'));
expectType<string[]>(await MyModel.distinct<string>('name'));
expectType<unknown[]>(await MyModel.distinct('notThereInSchema'));
expectType<string[]>(await MyModel.distinct('name'));
expectType<number[]>(await MyModel.distinct<'overrideTest', number>('overrideTest'));
}

function autoTypedQuery() {
Expand Down
7 changes: 5 additions & 2 deletions types/models.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReturnType = any>(field: string, filter?: FilterQuery<TRawDocType>): QueryWithHelpers<
Array<ReturnType>,
distinct<DocKey extends string, ResultType = unknown>(
field: DocKey,
filter?: FilterQuery<TRawDocType>
): QueryWithHelpers<
Array<DocKey extends keyof TRawDocType ? TRawDocType[DocKey] : ResultType>,
THydratedDocumentType,
TQueryHelpers,
TRawDocType,
Expand Down
6 changes: 3 additions & 3 deletions types/query.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,10 +317,10 @@ declare module 'mongoose' {
deleteOne(): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteOne'>;

/** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
distinct<ReturnType = any>(
field: string,
distinct<DocKey extends string, ResultType = unknown>(
field: DocKey,
filter?: FilterQuery<DocType>
): QueryWithHelpers<Array<ReturnType>, DocType, THelpers, RawDocType, 'distinct'>;
): QueryWithHelpers<Array<DocKey extends keyof DocType ? DocType[DocKey] : ResultType>, DocType, THelpers, RawDocType, 'distinct'>;

/** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
elemMatch<K = string>(path: K, val: any): this;
Expand Down

0 comments on commit b951883

Please sign in to comment.