Skip to content

Commit 50b2670

Browse files
committed
types: handle buffers in JSONSerialized and fix issue with DocumentArrays
1 parent ff24d86 commit 50b2670

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

test/types/schema.test.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1687,12 +1687,13 @@ async function gh14451() {
16871687
const exampleSchema = new Schema({
16881688
myId: { type: 'ObjectId' },
16891689
myRequiredId: { type: 'ObjectId', required: true },
1690+
myBuf: { type: Buffer, required: true },
16901691
subdoc: {
16911692
type: new Schema({
16921693
subdocProp: Date
16931694
})
1694-
}
1695-
// docArr: [{ nums: [Number], times: [Date] }]
1695+
},
1696+
docArr: [{ nums: [Number], times: [{ type: Date }] }]
16961697
});
16971698

16981699
const Test = model('Test', exampleSchema);
@@ -1701,9 +1702,10 @@ async function gh14451() {
17011702
expectType<{
17021703
myId?: string | undefined | null,
17031704
myRequiredId: string,
1705+
myBuf: { type: 'buffer', data: number[] },
17041706
subdoc?: {
17051707
subdocProp?: string | undefined | null
17061708
} | null,
1707-
// docArr: { nums: number[], times: string[] }[]
1709+
docArr: { nums: number[], times: string[] }[]
17081710
}>({} as TestJSON);
17091711
}

types/index.d.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,18 @@ declare module 'mongoose' {
718718
: BufferToBinary<T[K]>;
719719
} : T;
720720

721+
export type BufferToJSON<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
722+
[K in keyof T]: T[K] extends Buffer
723+
? { type: 'buffer', data: number[] }
724+
: T[K] extends (Buffer | null | undefined)
725+
? { type: 'buffer', data: number[] } | null | undefined
726+
: T[K] extends Types.DocumentArray<infer ItemType>
727+
? Types.DocumentArray<BufferToBinary<ItemType>>
728+
: T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
729+
? HydratedSingleSubdocument<SubdocType>
730+
: BufferToBinary<T[K]>;
731+
} : T;
732+
721733
export type ObjectIdToString<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
722734
[K in keyof T]: T[K] extends mongodb.ObjectId
723735
? string
@@ -748,16 +760,18 @@ declare module 'mongoose' {
748760
: T[K] extends (NativeDate | null | undefined)
749761
? string | null | undefined
750762
: T[K] extends Types.DocumentArray<infer ItemType>
751-
? ItemType
763+
? ItemType[]
752764
: T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
753765
? SubdocType
754766
: SubdocsToPOJOs<T[K]>;
755767
} : T;
756768

757769
export type JSONSerialized<T> = SubdocsToPOJOs<
758770
FlattenMaps<
759-
ObjectIdToString<
760-
DateToString<T>
771+
BufferToJSON<
772+
ObjectIdToString<
773+
DateToString<T>
774+
>
761775
>
762776
>
763777
>;

0 commit comments

Comments
 (0)