Skip to content

Commit

Permalink
Handle DocumentArray in FlattenMaps
Browse files Browse the repository at this point in the history
  • Loading branch information
Jokero committed May 1, 2023
1 parent c3d1e8e commit 4055c64
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
40 changes: 38 additions & 2 deletions test/types/lean.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Schema, model, Document, Types } from 'mongoose';
import { expectError, expectType } from 'tsd';
import { Schema, model, Document, Types, InferSchemaType, FlattenMaps } from 'mongoose';
import { expectAssignable, expectError, expectType } from 'tsd';

function gh10345() {
(function() {
Expand Down Expand Up @@ -143,3 +143,39 @@ async function gh13010() {
const country = await CountryModel.findOne().lean().orFail().exec();
expectType<Record<string, string>>(country.name);
}

async function gh13345_1() {
const imageSchema = new Schema({
url: { required: true, type: String }
});

const placeSchema = new Schema({
images: { required: true, type: [imageSchema] }
});

type Place = InferSchemaType<typeof placeSchema>;

const PlaceModel = model('Place', placeSchema);

const place = await PlaceModel.findOne().lean().orFail().exec();
expectAssignable<Place>(place);
}

async function gh13345_2() {
const imageSchema = new Schema({
description: { required: true, type: Map, of: String },
url: { required: true, type: String }
});

const placeSchema = new Schema({
images: { required: true, type: [imageSchema] }
});

type Place = InferSchemaType<typeof placeSchema>;

const PlaceModel = model('Place', placeSchema);

const place = await PlaceModel.findOne().lean().orFail().exec();
expectAssignable<FlattenMaps<Place>>(place);
expectType<Record<string, string>>(place.images[0].description);
}
3 changes: 2 additions & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,8 @@ declare module 'mongoose' {
export type FlattenMaps<T> = {
[K in keyof T]: T[K] extends Map<any, infer V>
? Record<string, V> : T[K] extends TreatAsPrimitives
? T[K] : FlattenMaps<T[K]>;
? T[K] : T[K] extends Types.DocumentArray<infer ItemType>
? Types.DocumentArray<FlattenMaps<ItemType>> : FlattenMaps<T[K]>;
};

export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
Expand Down

0 comments on commit 4055c64

Please sign in to comment.