diff --git a/index.d.ts b/index.d.ts index e74b6ac91e9..fafeab995ed 100644 --- a/index.d.ts +++ b/index.d.ts @@ -2125,6 +2125,8 @@ declare module 'mongoose' { type UnpackedIntersection = T extends (infer V)[] ? (V & U)[] : T & U; + type ProjectionFields = {[Key in keyof Omit, '__v'>]?: any} & Record; + class Query { _mongooseOptions: MongooseQueryOptions; @@ -2411,7 +2413,9 @@ declare module 'mongoose' { populate(options: PopulateOptions | Array): QueryWithHelpers, DocType, THelpers, RawDocType>; /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */ - projection(fields?: any | null): this; + projection(): ProjectionFields | null; + projection(fields: null): null; + projection(fields?: ProjectionFields | string): ProjectionFields; /** Determines the MongoDB nodes from which to read. */ read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this; diff --git a/test/typescript/queries.ts b/test/typescript/queries.ts index c36df4c2546..422f6ed1a93 100644 --- a/test/typescript/queries.ts +++ b/test/typescript/queries.ts @@ -116,6 +116,17 @@ query instanceof Query; Test.findOne().where({ name: 'test' }); Test.where().find({ name: 'test' }); +// Projection +const p0: Record = Test.find().projection({ + age: true, + parent: 1, + 'docs.id': 1 +}); +const p1: Record = Test.find().projection('age docs.id'); +const p2: Record | null = Test.find().projection(); +const p3: null = Test.find().projection(null); + + // Super generic query function testGenericQuery(): void { interface CommonInterface extends Document { @@ -200,4 +211,4 @@ async function gh11156(): Promise { const User: Model = model('User', schema); const overwritten: User = await User.findOne>({}).orFail(); -} \ No newline at end of file +}