Skip to content

Commit 0b152ee

Browse files
committed
recursively convert buffer to binary
1 parent 8825b76 commit 0b152ee

File tree

3 files changed

+16
-7
lines changed

3 files changed

+16
-7
lines changed

test/types/schema.test.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1667,12 +1667,17 @@ async function gh14950() {
16671667
}
16681668

16691669
async function gh14902() {
1670-
const def = {
1671-
image: { type: Buffer }
1672-
} as const;
1673-
const exampleSchema = new Schema(def);
1670+
const exampleSchema = new Schema({
1671+
image: { type: Buffer },
1672+
subdoc: {
1673+
type: new Schema({
1674+
testBuf: Buffer
1675+
})
1676+
}
1677+
});
16741678
const Test = model('Test', exampleSchema);
16751679

16761680
const doc = await Test.findOne().lean().orFail();
16771681
expectType<Binary | null | undefined>(doc.image);
1682+
expectType<Binary | null | undefined>(doc.subdoc!.testBuf);
16781683
}

types/index.d.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -706,12 +706,16 @@ declare module 'mongoose' {
706706
[K in keyof T]: FlattenProperty<T[K]>;
707707
};
708708

709-
export type BufferToBinary<T> = T extends object ? {
709+
export type BufferToBinary<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
710710
[K in keyof T]: T[K] extends Buffer
711711
? mongodb.Binary
712712
: T[K] extends (Buffer | null | undefined)
713713
? mongodb.Binary | null | undefined
714-
: T[K];
714+
: T[K] extends Types.DocumentArray<infer ItemType>
715+
? Types.DocumentArray<BufferToBinary<ItemType>>
716+
: T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
717+
? HydratedSingleSubdocument<SubdocType>
718+
: BufferToBinary<T[K]>;
715719
} : T;
716720

717721
/**

types/query.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ declare module 'mongoose' {
211211
type QueryOpThatReturnsDocument = 'find' | 'findOne' | 'findOneAndUpdate' | 'findOneAndReplace' | 'findOneAndDelete';
212212

213213
type GetLeanResultType<RawDocType, ResultType, QueryOp> = QueryOp extends QueryOpThatReturnsDocument
214-
? (ResultType extends any[] ? Require_id<FlattenMaps<BufferToBinary<RawDocType>>>[] : Require_id<FlattenMaps<BufferToBinary<RawDocType>>>)
214+
? (ResultType extends any[] ? Require_id<BufferToBinary<FlattenMaps<RawDocType>>>[] : Require_id<BufferToBinary<FlattenMaps<RawDocType>>>)
215215
: ResultType;
216216

217217
type MergePopulatePaths<RawDocType, ResultType, QueryOp, Paths, TQueryHelpers, TInstanceMethods = Record<string, never>> = QueryOp extends QueryOpThatReturnsDocument

0 commit comments

Comments
 (0)