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

types: Fixes and improves Query.projection method signature #11210

Merged
merged 4 commits into from
Jan 20, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2125,6 +2125,8 @@ declare module 'mongoose' {

type UnpackedIntersection<T, U> = T extends (infer V)[] ? (V & U)[] : T & U;

type ProjectionFields<DocType> = {[Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any} & Record<string, any>;

class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
_mongooseOptions: MongooseQueryOptions;

Expand Down Expand Up @@ -2411,7 +2413,9 @@ declare module 'mongoose' {
populate<Paths = {}>(options: PopulateOptions | Array<PopulateOptions>): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, RawDocType>;

/** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */
projection(fields?: any | null): this;
projection(): ProjectionFields<DocType> | null;
projection(fields: null): null;
projection(fields?: ProjectionFields<DocType> | string): ProjectionFields<DocType>;

/** Determines the MongoDB nodes from which to read. */
read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
Expand Down
13 changes: 12 additions & 1 deletion test/typescript/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,17 @@ query instanceof Query;
Test.findOne().where({ name: 'test' });
Test.where().find({ name: 'test' });

// Projection
const p0: Record<string, number> = Test.find().projection({
age: true,
parent: 1,
'docs.id': 1
});
const p1: Record<string, number> = Test.find().projection('age docs.id');
const p2: Record<string, number> | null = Test.find().projection();
const p3: null = Test.find().projection(null);


// Super generic query
function testGenericQuery(): void {
interface CommonInterface<T> extends Document {
Expand Down Expand Up @@ -200,4 +211,4 @@ async function gh11156(): Promise<void> {
const User: Model<User> = model<User>('User', schema);

const overwritten: User = await User.findOne<Pick<User, 'name'>>({}).orFail();
}
}