Skip to content

Commit

Permalink
add docs and test coverage for maps
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Oct 25, 2024
1 parent 50b2670 commit 858cc0a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
9 changes: 7 additions & 2 deletions test/types/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1693,7 +1693,11 @@ async function gh14451() {
subdocProp: Date
})
},
docArr: [{ nums: [Number], times: [{ type: Date }] }]
docArr: [{ nums: [Number], times: [{ type: Date }] }],
myMap: {
type: Map,
of: String
}
});

const Test = model('Test', exampleSchema);
Expand All @@ -1706,6 +1710,7 @@ async function gh14451() {
subdoc?: {
subdocProp?: string | undefined | null
} | null,
docArr: { nums: number[], times: string[] }[]
docArr: { nums: number[], times: string[] }[],
myMap?: Record<string, string> | null | undefined
}>({} as TestJSON);
}
15 changes: 15 additions & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -706,6 +706,9 @@ declare module 'mongoose' {
[K in keyof T]: FlattenProperty<T[K]>;
};

/**
* Converts any Buffer properties into mongodb.Binary instances, which is what `lean()` returns
*/
export type BufferToBinary<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
[K in keyof T]: T[K] extends Buffer
? mongodb.Binary
Expand All @@ -718,6 +721,9 @@ declare module 'mongoose' {
: BufferToBinary<T[K]>;
} : T;

/**
* Converts any Buffer properties into { type: 'buffer', data: [1, 2, 3] } format for JSON serialization
*/
export type BufferToJSON<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
[K in keyof T]: T[K] extends Buffer
? { type: 'buffer', data: number[] }
Expand All @@ -730,6 +736,9 @@ declare module 'mongoose' {
: BufferToBinary<T[K]>;
} : T;

/**
* Converts any ObjectId properties into strings for JSON serialization
*/
export type ObjectIdToString<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
[K in keyof T]: T[K] extends mongodb.ObjectId
? string
Expand All @@ -742,6 +751,9 @@ declare module 'mongoose' {
: ObjectIdToString<T[K]>;
} : T;

/**
* Converts any Date properties into strings for JSON serialization
*/
export type DateToString<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
[K in keyof T]: T[K] extends NativeDate
? string
Expand All @@ -754,6 +766,9 @@ declare module 'mongoose' {
: DateToString<T[K]>;
} : T;

/**
* Converts any Mongoose subdocuments (single nested or doc arrays) into POJO equivalents
*/
export type SubdocsToPOJOs<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
[K in keyof T]: T[K] extends NativeDate
? string
Expand Down

0 comments on commit 858cc0a

Please sign in to comment.