Skip to content

Commit

Permalink
Merge pull request #11210 from EugeneKorshenko/fix/types/projection
Browse files Browse the repository at this point in the history
types: Fixes and improves `Query.projection` method signature
  • Loading branch information
vkarpov15 authored Jan 20, 2022
2 parents 87ee959 + ce550cc commit d6898a7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
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();
}
}

0 comments on commit d6898a7

Please sign in to comment.