Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BREAKING CHANGE: Safer types for Model.distinct and Query.distinct. #13836

Merged
merged 1 commit into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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