Skip to content

types: automatically infer discriminator type #15547

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

Merged
merged 7 commits into from
Jul 25, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmarks/typescript/simple/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"dependencies": {
"mongoose": "file:../../../mongoose.tgz",
"typescript": "5.5.x"
"typescript": "5.8.x"
},
"scripts": {
"benchmark": "tsc --extendedDiagnostics"
Expand Down
40 changes: 40 additions & 0 deletions test/types/discriminator.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mongoose, { Document, Model, Schema, SchemaDefinition, SchemaOptions, Types, model } from 'mongoose';
import { expectType } from 'tsd';

const schema: Schema = new Schema({ name: { type: 'String' } });

Expand Down Expand Up @@ -76,3 +77,42 @@ function test(): void {

const sampleCardDb: CardDb = sampleLandDb;
}

function gh15535() {
const ParentSchema = new Schema({
field1: {
type: String,
required: true
},
field2: Number
}, {
discriminatorKey: 'field1',
methods: {
getField2() {
return this.field2;
}
}
});

const ParentModel = mongoose.model('Parent', ParentSchema);

const ChildSchema = new Schema({
field3: String
}, {
methods: {
getField3() {
return this.field3;
}
}
});


const ChildModel = ParentModel.discriminator('child', ChildSchema);

const doc = new ChildModel({});
expectType<string>(doc.field1);
expectType<number | null | undefined>(doc.field2);
expectType<number | null | undefined>(doc.getField2());
expectType<string | null | undefined>(doc.field3);
expectType<string | null | undefined>(doc.getField3());
}
2 changes: 1 addition & 1 deletion test/types/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ export function autoTypedSchema() {
}, {
statics: {
staticFn() {
expectType<Model<InferSchemaType<typeof AutoTypedSchema>>>(this);
expectAssignable<Model<InferSchemaType<typeof AutoTypedSchema>>>(this);
return 'Returned from staticFn' as const;
}
},
Expand Down
7 changes: 1 addition & 6 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ declare module 'mongoose' {
| typeof Schema.Types.UUID;


export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
export type InferId<T> = mongodb.InferIdType<T>;

export interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
/** If `ref` is not nullish, this becomes a populated virtual. */
Expand Down Expand Up @@ -902,11 +902,6 @@ declare module 'mongoose' {

export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;

/**
* Helper to choose the best option between two type helpers
*/
export type _pickObject<T1, T2, Fallback> = T1 extends false ? T2 extends false ? Fallback : T2 : T1;

/* for ts-mongoose */
export class mquery { }

Expand Down
29 changes: 25 additions & 4 deletions types/models.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,6 @@ declare module 'mongoose' {
THydratedDocumentType = HydratedDocument<TRawDocType, TVirtuals & TInstanceMethods, TQueryHelpers, TVirtuals>,
TSchema = any> extends
NodeJS.EventEmitter,
AcceptsDiscriminator,
IndexManager,
SessionStarter {
new <DocType = Partial<TRawDocType>>(doc?: DocType, fields?: any | null, options?: boolean | AnyObject): THydratedDocumentType;
Expand Down Expand Up @@ -313,11 +312,11 @@ declare module 'mongoose' {
* round trip to the MongoDB server.
*/
bulkWrite<DocContents = TRawDocType>(
writes: Array<AnyBulkWriteOperation<DocContents extends Document ? any : (DocContents extends {} ? DocContents : any)>>,
writes: Array<AnyBulkWriteOperation<DocContents>>,
options: MongooseBulkWriteOptions & { ordered: false }
): Promise<MongooseBulkWriteResult>;
bulkWrite<DocContents = TRawDocType>(
writes: Array<AnyBulkWriteOperation<DocContents extends Document ? any : (DocContents extends {} ? DocContents : any)>>,
writes: Array<AnyBulkWriteOperation<DocContents>>,
options?: MongooseBulkWriteOptions
): Promise<MongooseBulkWriteResult>;

Expand Down Expand Up @@ -426,6 +425,28 @@ declare module 'mongoose' {
TInstanceMethods & TVirtuals
>;

/** Adds a discriminator type. */
discriminator<TDiscriminatorSchema extends Schema<any, any>>(
name: string | number,
schema: TDiscriminatorSchema,
value?: string | number | ObjectId | DiscriminatorOptions
): Model<
TRawDocType & InferSchemaType<TDiscriminatorSchema>,
TQueryHelpers & ObtainSchemaGeneric<TDiscriminatorSchema, 'TQueryHelpers'>,
TInstanceMethods & ObtainSchemaGeneric<TDiscriminatorSchema, 'TInstanceMethods'>,
TVirtuals & ObtainSchemaGeneric<TDiscriminatorSchema, 'TVirtuals'>
> & ObtainSchemaGeneric<TDiscriminatorSchema, 'TStaticMethods'>;
discriminator<D>(
name: string | number,
schema: Schema,
value?: string | number | ObjectId | DiscriminatorOptions
): Model<D>;
discriminator<T, U>(
name: string | number,
schema: Schema<T, U>,
value?: string | number | ObjectId | DiscriminatorOptions
): U;

/**
* Delete an existing [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) by name.
* This function only works when connected to MongoDB Atlas.
Expand Down Expand Up @@ -885,7 +906,7 @@ declare module 'mongoose' {
replaceOne<ResultDoc = THydratedDocumentType>(
filter?: RootFilterQuery<TRawDocType>,
replacement?: TRawDocType | AnyObject,
options?: (mongodb.ReplaceOptions & MongooseQueryOptions<TRawDocType>) | null
options?: (mongodb.ReplaceOptions & QueryOptions<TRawDocType>) | null
): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, TRawDocType, 'replaceOne', TInstanceMethods & TVirtuals>;

/** Apply changes made to this model's schema after this model was compiled. */
Expand Down
18 changes: 4 additions & 14 deletions types/query.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,9 @@ declare module 'mongoose' {
| 'strictQuery'
| 'translateAliases';

type MongooseQueryOptions<
DocType = unknown,
Keys extends keyof QueryOptions<DocType> = MongooseBaseQueryOptionKeys | 'timestamps' | 'lean'
> = Pick<QueryOptions<DocType>, Keys> & {
[other: string]: any;
};
type MongooseBaseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, MongooseBaseQueryOptionKeys>;

type MongooseBaseQueryOptions<DocType = unknown> = MongooseQueryOptions<DocType, MongooseBaseQueryOptionKeys>;

type MongooseUpdateQueryOptions<DocType = unknown> = MongooseQueryOptions<
DocType,
MongooseBaseQueryOptionKeys | 'timestamps'
>;
type MongooseUpdateQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, MongooseBaseQueryOptionKeys | 'timestamps'>;

type ProjectionFields<DocType> = { [Key in keyof DocType]?: any } & Record<string, any>;

Expand Down Expand Up @@ -239,7 +229,7 @@ declare module 'mongoose' {
: MergeType<ResultType, Paths>;

class Query<ResultType, DocType, THelpers = {}, RawDocType = unknown, QueryOp = 'find', TDocOverrides = Record<string, never>> implements SessionOperation {
_mongooseOptions: MongooseQueryOptions<DocType>;
_mongooseOptions: QueryOptions<DocType>;

/**
* Returns a wrapper around a [mongodb driver cursor](https://mongodb.github.io/node-mongodb-native/4.9/classes/FindCursor.html).
Expand Down Expand Up @@ -634,7 +624,7 @@ declare module 'mongoose' {
* Getter/setter around the current mongoose-specific options for this query
* Below are the current Mongoose-specific options.
*/
mongooseOptions(val?: MongooseQueryOptions): MongooseQueryOptions;
mongooseOptions(val?: QueryOptions<DocType>): QueryOptions<DocType>;

/** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
ne<K = string>(path: K, val: any): this;
Expand Down