Skip to content

Commit 904c436

Browse files
committed
types(DocumentArray): pass DocType generic to Document for correct toJSON() and toObject() return types
Fix #14469
1 parent 78bbcb5 commit 904c436

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

test/types/docArray.test.ts

+36-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Schema, model, Types, InferSchemaType } from 'mongoose';
1+
import { Schema, model, Model, Types, InferSchemaType } from 'mongoose';
22
import { expectError, expectType } from 'tsd';
33

44
async function gh10293() {
@@ -127,3 +127,38 @@ async function gh14367() {
127127
expectType<boolean | null | undefined>({} as IUser['reminders'][0]['toggle']);
128128
expectType<string | null | undefined>({} as IUser['avatar']);
129129
}
130+
131+
function gh14469() {
132+
interface Names {
133+
_id: Types.ObjectId;
134+
firstName: string;
135+
}
136+
// Document definition
137+
interface User {
138+
names: Names[];
139+
}
140+
141+
// TMethodsAndOverrides
142+
type UserDocumentProps = {
143+
names: Types.DocumentArray<Names>;
144+
};
145+
type UserModelType = Model<User, {}, UserDocumentProps>;
146+
147+
const userSchema = new Schema<User, UserModelType>(
148+
{
149+
names: [new Schema<Names>({ firstName: String })]
150+
},
151+
{ timestamps: true }
152+
);
153+
154+
// Create model
155+
const UserModel = model<User, UserModelType>('User', userSchema);
156+
157+
const doc = new UserModel({ names: [{ firstName: 'John' }] });
158+
159+
const jsonDoc = doc?.toJSON();
160+
expectType<string>(jsonDoc?.names[0]?.firstName);
161+
162+
const jsonNames = doc?.names[0]?.toJSON();
163+
expectType<string>(jsonNames?.firstName);
164+
}

types/types.d.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ declare module 'mongoose' {
6060

6161
class Decimal128 extends mongodb.Decimal128 { }
6262

63-
class DocumentArray<T> extends Types.Array<T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T> {
63+
class DocumentArray<T> extends Types.Array<T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>, any, T> & T> {
6464
/** DocumentArray constructor */
6565
constructor(values: AnyObject[]);
6666

@@ -83,7 +83,7 @@ declare module 'mongoose' {
8383
class ObjectId extends mongodb.ObjectId {
8484
}
8585

86-
class Subdocument<IdType = any> extends Document<IdType> {
86+
class Subdocument<IdType = any, TQueryHelpers = any, DocType = any> extends Document<IdType, TQueryHelpers, DocType> {
8787
$isSingleNested: true;
8888

8989
/** Returns the top level document of this sub-document. */

0 commit comments

Comments
 (0)