Skip to content

Commit 2e5b780

Browse files
authored
Merge pull request #16021 from Automattic/fix/gh-15965-subdoc-toObject
fix(types): preserve subdocument toObject() field types when using virtuals + versionKey options
2 parents 324ff4c + 684b31f commit 2e5b780

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

test/types/document.test.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,33 @@ function gh15965() {
501501
ExpectType<Date>(obj.updatedAt);
502502
}
503503

504+
function gh15965SubdocToObject() {
505+
const documentSchema = new Schema({
506+
title: { type: String, required: true },
507+
text: { type: String, required: true }
508+
});
509+
510+
const podcastSchema = new Schema({
511+
documents: [documentSchema]
512+
}, {
513+
timestamps: true,
514+
virtuals: { hello: { get() { return 'world'; } } }
515+
});
516+
517+
const Podcast = model('Podcast', podcastSchema);
518+
const podcast = new Podcast({ documents: [{ title: 'test', text: 'body' }] });
519+
const subdoc = podcast.documents[0];
520+
521+
const obj = subdoc.toObject({ flattenObjectIds: true, versionKey: false, virtuals: true });
522+
523+
// @ts-expect-error title should be string, not any
524+
const _titleCheck: number = obj.title;
525+
// @ts-expect-error text should be string, not any
526+
const _textCheck: number = obj.text;
527+
// @ts-expect-error no index signature: nonexistent properties should be a type error
528+
obj.doesNotExist;
529+
}
530+
504531
function gh13079() {
505532
const schema = new Schema({
506533
name: { type: String, required: true }

types/types.d.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ declare module 'mongoose' {
8484
class ObjectId extends mongodb.ObjectId {
8585
}
8686

87-
class Subdocument<IdType = any, TQueryHelpers = any, DocType = any> extends Document<IdType, TQueryHelpers, DocType> {
87+
class Subdocument<IdType = any, TQueryHelpers = any, DocType = any, TVirtuals = {}, TSchemaOptions = {}> extends Document<IdType, TQueryHelpers, DocType, TVirtuals, TSchemaOptions> {
8888
$isSingleNested: true;
8989

9090
/** Returns the top level document of this sub-document. */
@@ -97,7 +97,7 @@ declare module 'mongoose' {
9797
$parent(): Document;
9898
}
9999

100-
class ArraySubdocument<IdType = any, TQueryHelpers = unknown, DocType = unknown> extends Subdocument<IdType, TQueryHelpers, DocType> {
100+
class ArraySubdocument<IdType = any, TQueryHelpers = unknown, DocType = unknown, TVirtuals = {}, TSchemaOptions = {}> extends Subdocument<IdType, TQueryHelpers, DocType, TVirtuals, TSchemaOptions> {
101101
/** Returns this sub-documents parent array. */
102102
parentArray(): Types.DocumentArray<unknown>;
103103
}

0 commit comments

Comments
 (0)