Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types(DocumentArray): pass DocType generic to Document for correct toJSON() and toObject() return types #14526

Merged
merged 1 commit into from Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 36 additions & 1 deletion test/types/docArray.test.ts
@@ -1,4 +1,4 @@
import { Schema, model, Types, InferSchemaType } from 'mongoose';
import { Schema, model, Model, Types, InferSchemaType } from 'mongoose';
import { expectError, expectType } from 'tsd';

async function gh10293() {
Expand Down Expand Up @@ -127,3 +127,38 @@ async function gh14367() {
expectType<boolean | null | undefined>({} as IUser['reminders'][0]['toggle']);
expectType<string | null | undefined>({} as IUser['avatar']);
}

function gh14469() {
interface Names {
_id: Types.ObjectId;
firstName: string;
}
// Document definition
interface User {
names: Names[];
}

// TMethodsAndOverrides
type UserDocumentProps = {
names: Types.DocumentArray<Names>;
};
type UserModelType = Model<User, {}, UserDocumentProps>;

const userSchema = new Schema<User, UserModelType>(
{
names: [new Schema<Names>({ firstName: String })]
},
{ timestamps: true }
);

// Create model
const UserModel = model<User, UserModelType>('User', userSchema);

const doc = new UserModel({ names: [{ firstName: 'John' }] });

const jsonDoc = doc?.toJSON();
expectType<string>(jsonDoc?.names[0]?.firstName);

const jsonNames = doc?.names[0]?.toJSON();
expectType<string>(jsonNames?.firstName);
}
4 changes: 2 additions & 2 deletions types/types.d.ts
Expand Up @@ -60,7 +60,7 @@ declare module 'mongoose' {

class Decimal128 extends mongodb.Decimal128 { }

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

Expand All @@ -83,7 +83,7 @@ declare module 'mongoose' {
class ObjectId extends mongodb.ObjectId {
}

class Subdocument<IdType = any> extends Document<IdType> {
class Subdocument<IdType = any, TQueryHelpers = any, DocType = any> extends Document<IdType, TQueryHelpers, DocType> {
$isSingleNested: true;

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