/// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// declare class NativeDate extends globalThis.Date { } declare module 'mongoose' { import Kareem = require('kareem'); import events = require('events'); import mongodb = require('mongodb'); import mongoose = require('mongoose'); export type Mongoose = typeof mongoose; /** * Mongoose constructor. The exports object of the `mongoose` module is an instance of this * class. Most apps will only use this one instance. */ export const Mongoose: new (options?: MongooseOptions | null) => Mongoose; export let Promise: any; /** * Can be extended to explicitly type specific models. */ export interface Models { [modelName: string]: Model } /** An array containing all models associated with this Mongoose instance. */ export const models: Models; /** * Removes the model named `name` from the default connection, if it exists. * You can use this function to clean up any models you created in your tests to * prevent OverwriteModelErrors. */ export function deleteModel(name: string | RegExp): Mongoose; /** * Sanitizes query filters against query selector injection attacks by wrapping * any nested objects that have a property whose name starts with `$` in a `$eq`. */ export function sanitizeFilter(filter: QueryFilter): QueryFilter; /** Gets mongoose options */ export function get(key: K): MongooseOptions[K]; export function omitUndefined>(val: T): T; export type HydratedDocFromModel> = ReturnType; /* ! ignore */ export type CompileModelOptions = { overwriteModels?: boolean, connection?: Connection }; export function model( name: string, schema?: TSchema, collection?: string, options?: CompileModelOptions ): Model< InferSchemaType, ObtainSchemaGeneric, ObtainSchemaGeneric, ObtainSchemaGeneric, // If first schema generic param is set, that means we have an explicit raw doc type, // so user should also specify a hydrated doc type if the auto inferred one isn't correct. IsItRecordAndNotAny> extends true ? ObtainSchemaGeneric : HydratedDocument< InferSchemaType, ObtainSchemaGeneric & ObtainSchemaGeneric, ObtainSchemaGeneric, ObtainSchemaGeneric, InferSchemaType, ObtainSchemaGeneric >, TSchema, ObtainSchemaGeneric > & ObtainSchemaGeneric; export function model(name: string, schema?: Schema | Schema, collection?: string, options?: CompileModelOptions): Model; export function model( name: string, schema?: Schema, collection?: string, options?: CompileModelOptions ): U; /** Returns an array of model names created on this instance of Mongoose. */ export function modelNames(): Array; /** * Overwrites the current driver used by this Mongoose instance. A driver is a * Mongoose-specific interface that defines functions like `find()`. */ export function setDriver(driver: any): Mongoose; /** The node-mongodb-native driver Mongoose uses. */ export { mongodb as mongo }; /** Declares a global plugin executed on all Schemas. */ export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Mongoose; /** Getter/setter around function for pluralizing collection names. */ export function pluralize(fn?: ((str: string) => string) | null): ((str: string) => string) | null; /** Sets mongoose options */ export function set(key: K, value: MongooseOptions[K]): Mongoose; export function set(options: { [K in keyof MongooseOptions]: MongooseOptions[K] }): Mongoose; /** The Mongoose version */ export const version: string; export type AnyKeys = { [P in keyof T]?: T[P] | any }; export interface AnyObject { [k: string]: any } export type Require_id = T extends { _id?: infer U } ? IfAny> : T & { _id: Types.ObjectId }; export type Default__v = TSchemaOptions extends { versionKey: false } ? T : TSchemaOptions extends { versionKey: infer VK } ? ( // If VK is a *literal* string, add that property T & { [K in VK as K extends string ? (string extends K ? never : K) // drop if wide string : never ]: number } ) : T extends { __v?: infer U } ? T : T & { __v: number }; /** Helper type for getting the hydrated document type from the raw document type. The hydrated document type is what `new MyModel()` returns. */ export type HydratedDocument< HydratedDocPathsType, TOverrides = {}, TQueryHelpers = {}, TVirtuals = {}, RawDocType = HydratedDocPathsType, TSchemaOptions = DefaultSchemaOptions > = IfAny< HydratedDocPathsType, any, TOverrides extends Record ? Document & Default__v, TSchemaOptions> & IfEquals< TVirtuals, {}, AddDefaultId, TVirtuals > : IfAny< TOverrides, Document & Default__v, TSchemaOptions>, Document & MergeType< Default__v, TSchemaOptions>, IfEquals< TOverrides, {}, TOverrides, TOverrides & AddDefaultId > > > >; export type HydratedSingleSubdocument< DocType, TOverrides = {} > = IfAny< DocType, any, TOverrides extends Record ? Types.Subdocument, DocType> & Require_id : IfAny< TOverrides, Types.Subdocument, DocType> & Require_id, Types.Subdocument, DocType> & MergeType< Require_id, TOverrides > > >; export type HydratedArraySubdocument = IfAny< DocType, any, TOverrides extends Record ? Types.ArraySubdocument, DocType> & Require_id : IfAny< TOverrides, Types.ArraySubdocument, DocType> & Require_id, Types.ArraySubdocument, DocType> & MergeType< Require_id, TOverrides > > >; export type HydratedDocumentFromSchema = HydratedDocument< InferSchemaType, ObtainSchemaGeneric & ObtainSchemaGeneric, ObtainSchemaGeneric, ObtainSchemaGeneric, InferSchemaType, ObtainSchemaGeneric >; export interface TagSet { [k: string]: string; } export interface ToObjectOptions> { /** if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. */ aliases?: boolean; /** if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. */ depopulate?: boolean; /** if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. */ flattenMaps?: boolean; /** if true, convert any ObjectIds in the result to 24 character hex strings. */ flattenObjectIds?: boolean; /** if true, convert any UUIDs in the result to 36 character hex strings. */ flattenUUIDs?: boolean; /** apply all getters (path and virtual getters) */ getters?: boolean; /** remove empty objects (defaults to true) */ minimize?: boolean; /** If true, the resulting object will only have fields that are defined in the document's schema. By default, `toJSON()` & `toObject()` returns all fields in the underlying document from MongoDB, including ones that are not listed in the schema. */ schemaFieldsOnly?: boolean; /** if set, mongoose will call this function to allow you to transform the returned object */ transform?: boolean | (( doc: THydratedDocumentType, ret: Default__v>, options: ToObjectOptions ) => any); /** If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. */ useProjection?: boolean; /** if false, exclude the version key (`__v` by default) from the output */ versionKey?: boolean; /** apply virtual getters (can override getters option) */ virtuals?: boolean | string[]; } export type DiscriminatorModel = T extends Model ? M extends Model ? Model & T, MQueryHelpers | TQueryHelpers, MInstanceMethods | TInstanceMethods, MVirtuals | TVirtuals> : M : M; export type DiscriminatorSchema = DisSchema extends Schema ? Schema, DiscriminatorModel, DisSchemaInstanceMethods | TInstanceMethods, DisSchemaQueryhelpers | TQueryHelpers, DisSchemaVirtuals | TVirtuals, DisSchemaStatics & TStaticMethods> : Schema; type QueryResultType = T extends Query ? ResultType : never; type PluginFunction< DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods> = (schema: Schema, opts?: any) => void; export class Schema< RawDocType = any, TModelType = Model, TInstanceMethods = {}, TQueryHelpers = {}, TVirtuals = {}, TStaticMethods = {}, TSchemaOptions = DefaultSchemaOptions, DocType extends ApplySchemaOptions< ObtainDocumentType>, ResolveSchemaOptions > = ApplySchemaOptions< ObtainDocumentType>, ResolveSchemaOptions >, THydratedDocumentType = HydratedDocument< DocType, AddDefaultId & TInstanceMethods, TQueryHelpers, AddDefaultId, IsItRecordAndNotAny extends true ? RawDocType : DocType, ResolveSchemaOptions >, TSchemaDefinition = IfAny, RawDocType, THydratedDocumentType>>, LeanResultType = IsItRecordAndNotAny extends true ? RawDocType : Default__v>>> > extends events.EventEmitter { /** * Create a new schema */ constructor( definition?: SchemaDefinition, RawDocType, THydratedDocumentType> | DocType, options?: SchemaOptions< FlatRecord, TInstanceMethods, TQueryHelpers, TStaticMethods, TVirtuals, THydratedDocumentType, IfEquals< TModelType, Model, Model, TModelType > > | ResolveSchemaOptions ); /* Creates a new schema with the given definition and options. Equivalent to `new Schema(definition, options)`, but with better automatic type inference. */ static create< TSchemaDefinition extends SchemaDefinition, TSchemaOptions extends DefaultSchemaOptions, RawDocType extends ApplySchemaOptions< InferRawDocType>, ResolveSchemaOptions >, THydratedDocumentType extends AnyObject = HydratedDocument< InferHydratedDocType>, TSchemaOptions extends { methods: infer M } ? M : {}, TSchemaOptions extends { query: any } ? TSchemaOptions['query'] : {}, ResolveVirtuals, RawDocType, ResolveSchemaOptions > >(def: TSchemaDefinition): Schema< RawDocType, Model, TSchemaOptions extends { methods: infer M } ? M : {}, TSchemaOptions extends { query: any } ? TSchemaOptions['query'] : {}, ResolveVirtuals, TSchemaOptions extends { statics: any } ? TSchemaOptions['statics'] : {}, TSchemaOptions, ApplySchemaOptions< ObtainDocumentType>, ResolveSchemaOptions >, THydratedDocumentType, TSchemaDefinition, ApplySchemaOptions< InferRawDocType, { bufferToBinary: true }>, ResolveSchemaOptions > >; static create< TSchemaDefinition extends SchemaDefinition, TSchemaOptions extends SchemaOptions>, RawDocType extends ApplySchemaOptions< InferRawDocType>, ResolveSchemaOptions >, TMethods = TSchemaOptions extends { methods: infer M } ? { [K in keyof M]: OmitThisParameter } : {}, TStatics = TSchemaOptions extends { statics: infer S } ? { [K in keyof S]: OmitThisParameter } : {} >(def: TSchemaDefinition, options: TSchemaOptions & { statics?: SchemaOptionsStaticsPropertyType< TStatics, Model > }): Schema< RawDocType, Model, TMethods, TSchemaOptions extends { query: any } ? TSchemaOptions['query'] : {}, ResolveVirtuals, TStatics, TSchemaOptions, ApplySchemaOptions< ObtainDocumentType>, ResolveSchemaOptions >, HydratedDocument< InferHydratedDocType>, TMethods, TSchemaOptions extends { query: any } ? TSchemaOptions['query'] : {}, ResolveVirtuals, RawDocType, ResolveSchemaOptions >, TSchemaDefinition, ApplySchemaOptions< InferRawDocType, { bufferToBinary: true }>, ResolveSchemaOptions > >; /** Adds key path / schema type pairs to this schema. */ add(obj: SchemaDefinition, RawDocType> | Schema, prefix?: string): this; /** * Add an alias for `path`. This means getting or setting the `alias` * is equivalent to getting or setting the `path`. */ alias(path: string, alias: string | string[]): this; /** * Array of child schemas (from document arrays and single nested subdocs) * and their corresponding compiled models. Each element of the array is * an object with 2 properties: `schema` and `model`. */ childSchemas: { schema: Schema, model: any }[]; /** Removes all indexes on this schema */ clearIndexes(): this; /** Returns a copy of this schema */ clone(): this; discriminator(name: string | number, schema: DisSchema, options?: DiscriminatorOptions): this; /** Returns a new schema that has the picked `paths` from this schema. */ pick(paths: string[], options?: SchemaOptions): T; /** Object containing discriminators defined on this schema */ discriminators?: { [name: string]: Schema }; /** Iterates the schemas paths similar to Array#forEach. */ eachPath(fn: (path: string, type: SchemaType) => void): this; /** Defines an index (most likely compound) for this schema. */ index(fields: IndexDefinition, options?: Omit & { unique?: boolean | [true, string] }): this; /** * Define a search index for this schema. * * @remarks Search indexes are only supported when used against a 7.0+ Mongo Atlas cluster. */ searchIndex(description: SearchIndexDescription): this; /** * Returns a list of indexes that this schema declares, via `schema.index()` * or by `index: true` in a path's options. */ indexes(): Array<[IndexDefinition, IndexOptions]>; /** Gets a schema option. */ get(key: K): SchemaOptions[K]; /** * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals), * [statics](http://mongoosejs.com/docs/guide.html#statics), and * [methods](http://mongoosejs.com/docs/guide.html#methods). */ loadClass(model: Function, onlyVirtuals?: boolean): this; /** Adds an instance method to documents constructed from Models compiled from this schema. */ method(name: string, fn: (this: Context, ...args: any[]) => any, opts?: any): this; method(obj: Partial): this; /** Object of currently defined methods on this schema. */ methods: AddThisParameter & AnyObject; /** The original object passed to the schema constructor */ obj: SchemaDefinition, RawDocType>; /** Returns a new schema that has the `paths` from the original schema, minus the omitted ones. */ omit(paths: string[], options?: SchemaOptions): T; options: SchemaOptions; /** Gets/sets schema paths. */ path>(path: string): ResultType; path(path: pathGeneric): SchemaType; path(path: string, constructor: any): this; /** Lists all paths and their type in the schema. */ paths: { [key: string]: SchemaType; }; /** Returns the pathType of `path` for this schema. */ pathType(path: string): string; /** Registers a plugin for this schema. */ plugin, POptions extends Parameters[1] = Parameters[1]>(fn: PFunc, opts?: POptions): this; plugin, any, any, any, any>, POptions extends Parameters[1] = Parameters[1]>(fn: PFunc, opts?: POptions): this; /** Defines a post hook for the model. */ // PostMiddlewareFunction // with errorHandler set to true post>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption): this; post(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption): this; post>(method: 'aggregate' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption>): this; post(method: 'insertMany' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption): this; // this = never since it never happens post(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: false }, fn: PostMiddlewareFunction): this; post(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions & { document: boolean, query: false }, fn: PostMiddlewareFunction>): this; post(method: MongooseDistinctDocumentMiddleware | MongooseDistinctDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: PostMiddlewareFunction): this; // this = Document post(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PostMiddlewareFunction): this; post(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & SchemaPostOptions, fn: PostMiddlewareFunction): this; post(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: PostMiddlewareFunction): this; post(method: 'init', fn: PostMiddlewareFunction): this; // this = Query post>(method: MongooseRawResultQueryMiddleware|MongooseRawResultQueryMiddleware[], fn: PostMiddlewareFunction | ModifyResult>>): this; post>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PostMiddlewareFunction>): this; post>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions, fn: PostMiddlewareFunction>): this; post>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: PostMiddlewareFunction>): this; // this = Union of Document and Query, could be called with any of them post>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: true }, fn: PostMiddlewareFunction>): this; post>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction>): this; // ErrorHandlingMiddlewareFunction // this = never since it never happens post(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions & { document: boolean, query: false }, fn: ErrorHandlingMiddlewareFunction): this; post(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & { document: false, query: boolean }, fn: ErrorHandlingMiddlewareFunction): this; post(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: false }, fn: ErrorHandlingMiddlewareFunction): this; // this = Document post(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: ErrorHandlingMiddlewareFunction): this; post(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this; post(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: ErrorHandlingMiddlewareFunction): this; // this = Query post>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: ErrorHandlingMiddlewareFunction): this; post>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this; post>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: ErrorHandlingMiddlewareFunction): this; // this = Union of Document and Query, could be called with any of them post>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: true }, fn: ErrorHandlingMiddlewareFunction): this; post>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction): this; // method aggregate and insertMany with PostMiddlewareFunction post>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction>>): this; post>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction>>): this; post(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction): this; post(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction): this; // method aggregate and insertMany with ErrorHandlingMiddlewareFunction post>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction>): this; post>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction>): this; post(method: 'bulkWrite' | 'createCollection' | 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction): this; post(method: 'bulkWrite' | 'createCollection' | 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction): this; /** Defines a pre hook for the model. */ // this = never since it never happens pre(method: 'save', options: SchemaPreOptions & { document: false, query: boolean }, fn: PreSaveMiddlewareFunction): this; pre(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: false }, fn: PreMiddlewareFunction): this; pre(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPreOptions & { document: boolean, query: false }, fn: PreMiddlewareFunction): this; pre(method: MongooseDistinctDocumentMiddleware | MongooseDistinctDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: boolean }, fn: PreMiddlewareFunction): this; // this = Union of Document and Query, could be called with any of them pre>( method: 'updateOne' | RegExp, options: SchemaPreOptions & { document: true, query: true }, fn: PreUpdateOneMiddlewareFunction ): this; pre>( method: 'deleteOne' | RegExp, options: SchemaPreOptions & { document: true, query: true }, fn: PreDeleteOneMiddlewareFunction ): this; // this = Document pre(method: 'save', fn: PreSaveMiddlewareFunction): this; pre(method: 'init', fn: (this: T, doc: U) => void): this; pre(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PreMiddlewareFunction): this; pre(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction): this; pre( method: 'updateOne' | RegExp, options: SchemaPreOptions & { document: true }, fn: PreUpdateOneMiddlewareFunction ): this; pre( method: 'deleteOne' | RegExp, options: SchemaPreOptions & { document: true }, fn: PreDeleteOneMiddlewareFunction ): this; pre(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: true, query: false }, fn: PreMiddlewareFunction): this; // this = Query pre>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PreMiddlewareFunction): this; pre>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction): this; pre>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: true }, fn: PreMiddlewareFunction): this; // this = Union of Document and Query, could be called with any of them pre>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: true, query: true }, fn: PreMiddlewareFunction): this; pre>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction): this; // method aggregate pre>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction): this; /* method insertMany */ pre( method: 'insertMany' | RegExp, fn: ( this: TModelType, docs: any | Array, options?: InsertManyOptions & { lean?: boolean } ) => void | Promise ): this; /* method bulkWrite */ pre( method: 'bulkWrite' | RegExp, fn: ( this: TModelType, ops: Array>, options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions ) => void | Promise ): this; /* method createCollection */ pre( method: 'createCollection' | RegExp, fn: ( this: TModelType, options?: mongodb.CreateCollectionOptions & Pick ) => void | Promise ): this; /** Object of currently defined query helpers on this schema. */ query: TQueryHelpers; /** Adds a method call to the queue. */ queue(name: string, args: any[]): this; /** Removes the given `path` (or [`paths`]). */ remove(paths: string | Array): this; /** Removes index by name or index spec */ removeIndex(index: string | AnyObject): this; /** Returns an Array of path strings that are required by this schema. */ requiredPaths(invalidate?: boolean): string[]; /** Sets a schema option. */ set(key: K, value: SchemaOptions[K], _tags?: any): this; /** Adds static "class" methods to Models compiled from this schema. */ static(name: K, fn: TStaticMethods[K]): this; static(obj: Partial & { [name: string]: (this: TModelType, ...args: any[]) => any }): this; static(name: string, fn: (this: TModelType, ...args: any[]) => any): this; /** Object of currently defined statics on this schema. */ statics: { [F in keyof TStaticMethods]: TStaticMethods[F] } & { [name: string]: (this: TModelType, ...args: any[]) => unknown }; toJSONSchema(options?: { useBsonType?: boolean }): Record; /** Creates a virtual type with the given name. */ virtual( name: keyof TVirtuals | string, options?: VirtualTypeOptions ): VirtualType; /** Object of currently defined virtuals on this schema */ virtuals: TVirtuals; /** Returns the virtual type with the given `name`. */ virtualpath(name: string): VirtualType | null; static ObjectId: typeof Schema.Types.ObjectId; } export type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number | Schema.Types.Number; export type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String | Schema.Types.String; export type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean | Schema.Types.Boolean; export type DateSchemaDefinition = DateConstructor | 'date' | 'Date' | typeof Schema.Types.Date | Schema.Types.Date; export type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId | Schema.Types.ObjectId | Types.ObjectId | typeof Types.ObjectId; export type BufferSchemaDefinition = typeof Buffer | 'buffer' | 'Buffer' | typeof Schema.Types.Buffer; export type Decimal128SchemaDefinition = 'decimal128' | 'Decimal128' | typeof Schema.Types.Decimal128 | Schema.Types.Decimal128 | Types.Decimal128; export type BigintSchemaDefinition = 'bigint' | 'BigInt' | typeof Schema.Types.BigInt | Schema.Types.BigInt | typeof BigInt | BigInt; export type UuidSchemaDefinition = 'uuid' | 'UUID' | typeof Schema.Types.UUID | Schema.Types.UUID; export type MapSchemaDefinition = MapConstructor | 'Map' | typeof Schema.Types.Map; export type UnionSchemaDefinition = 'Union' | 'union' | typeof Schema.Types.Union | Schema.Types.Union; export type DoubleSchemaDefinition = 'double' | 'Double' | typeof Schema.Types.Double | Schema.Types.Double; export type SchemaDefinitionWithBuiltInClass = T extends number ? NumberSchemaDefinition : T extends string ? StringSchemaDefinition : T extends boolean ? BooleanSchemaDefinition : T extends NativeDate ? DateSchemaDefinition : (Function | string); export type SchemaDefinitionProperty> = // ThisType intersection here avoids corrupting ThisType for SchemaTypeOptions (see test gh11828) | SchemaDefinitionWithBuiltInClass & ThisType | SchemaTypeOptions | typeof SchemaType | Schema | Schema[] | SchemaTypeOptions, EnforcedDocType, THydratedDocumentType>[] | Function[] | SchemaDefinition | SchemaDefinition, EnforcedDocType, THydratedDocumentType>[] | typeof Schema.Types.Mixed | MixedSchemaTypeOptions; export type SchemaDefinition> = T extends undefined ? { [path: string]: SchemaDefinitionProperty; } : { [path in keyof T]?: SchemaDefinitionProperty; }; export type AnyArray = T[] | ReadonlyArray; export type ExtractMongooseArray = T extends Types.Array ? AnyArray> : T; export interface MixedSchemaTypeOptions extends SchemaTypeOptions { type: typeof Schema.Types.Mixed; } export type RefType = | number | string | Buffer | undefined | Types.ObjectId | Types.Buffer | typeof Schema.Types.Number | typeof Schema.Types.String | typeof Schema.Types.Buffer | typeof Schema.Types.ObjectId | typeof Schema.Types.UUID; export type InferId = mongodb.InferIdType; export interface VirtualTypeOptions { /** If `ref` is not nullish, this becomes a populated virtual. */ ref?: string | Function; /** The local field to populate on if this is a populated virtual. */ localField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string); /** The foreign field to populate on if this is a populated virtual. */ foreignField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string); /** * By default, a populated virtual is an array. If you set `justOne`, * the populated virtual will be a single doc or `null`. */ justOne?: boolean; /** If you set this to `true`, Mongoose will call any custom getters you defined on this virtual. */ getters?: boolean; /** * If you set this to `true`, `populate()` will set this virtual to the number of populated * documents, as opposed to the documents themselves, using `Query#countDocuments()`. */ count?: boolean; /** Add an extra match condition to `populate()`. */ match?: QueryFilter | ((doc: Record, virtual?: this) => Record | null); /** Add a default `limit` to the `populate()` query. */ limit?: number; /** Add a default `skip` to the `populate()` query. */ skip?: number; /** * For legacy reasons, `limit` with `populate()` may give incorrect results because it only * executes a single query for every document being populated. If you set `perDocumentLimit`, * Mongoose will ensure correct `limit` per document by executing a separate query for each * document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` * will execute 2 additional queries if `.find()` returns 2 documents. */ perDocumentLimit?: number; /** Additional options like `limit` and `lean`. */ options?: QueryOptions & { match?: AnyObject }; /** If true and the given `name` is a direct child of an array, apply the virtual to the array rather than the elements. */ applyToArray?: boolean; /** Additional options for plugins */ [extra: string]: any; } export class VirtualType { /** Applies getters to `value`. */ applyGetters(value: any, doc: Document): any; /** Applies setters to `value`. */ applySetters(value: any, doc: Document): any; /** Adds a custom getter to this virtual. */ get(fn: (this: T, value: any, virtualType: VirtualType, doc: T) => any): this; /** Adds a custom setter to this virtual. */ set(fn: (this: T, value: any, virtualType: VirtualType, doc: T) => void): this; } export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' }; export type ArrayProjectionOperators = { $slice: number | [number, number]; $elemMatch?: never } | { $elemMatch: Record; $slice?: never }; /** * This Type Assigns `Element | undefined` recursively to the `T` type. * if it is an array it will do this to the element of the array, if it is an object it will do this for the properties of the object. * `Element` is the truthy or falsy values that are going to be used as the value of the projection.(1 | true or 0 | false) * For the elements of the array we will use: `Element | `undefined` | `ArrayProjectionOperators` * @example * type CalculatedType = Projector<{ a: string, b: number, c: { d: string }, d: string[] }, true> * type CalculatedType = { a?: true | undefined; b?: true | undefined; c?: true | { d?: true | undefined; } | undefined; d?: true | ArrayProjectionOperators | undefined; } */ export type Projector = T extends Array ? Projector | ArrayProjectionOperators : T extends TreatAsPrimitives ? Element : T extends Record ? { [K in keyof T]?: T[K] extends Record ? Projector | Element : Element; } : Element; type _IDType = { _id?: boolean | number }; export type InclusionProjection = IsItRecordAndNotAny extends true ? Omit, boolean | number>, '_id'> & _IDType : AnyObject; export type ExclusionProjection = IsItRecordAndNotAny extends true ? Omit, false | 0>, '_id'> & _IDType : AnyObject; export type ProjectionType = (InclusionProjection & AnyObject) | (ExclusionProjection & AnyObject) | string; export type SortValues = SortOrder; export type SortOrder = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending'; type _UpdateQuery = { /** @see https://www.mongodb.com/docs/manual/reference/operator/update-field/ */ $currentDate?: AnyKeys & AdditionalProperties; $inc?: AnyKeys & AdditionalProperties; $min?: AnyKeys & AdditionalProperties; $max?: AnyKeys & AdditionalProperties; $mul?: AnyKeys & AdditionalProperties; $rename?: Record; $set?: AnyKeys & AdditionalProperties; $setOnInsert?: AnyKeys & AdditionalProperties; $unset?: AnyKeys & AdditionalProperties; /** @see https://www.mongodb.com/docs/manual/reference/operator/update-array/ */ $addToSet?: AnyKeys & AdditionalProperties; $pop?: AnyKeys & AdditionalProperties; $pull?: AnyKeys & AdditionalProperties; $push?: AnyKeys & AdditionalProperties; $pullAll?: AnyKeys & AdditionalProperties; /** @see https://www.mongodb.com/docs/manual/reference/operator/update-bitwise/ */ $bit?: AnyKeys; }; export type UpdateWithAggregationPipeline = UpdateAggregationStage[]; export type UpdateAggregationStage = { $addFields: any } | { $set: any } | { $project: any } | { $unset: any } | { $replaceRoot: any } | { $replaceWith: any }; /** * Update query command to perform on the document * @example * ```js * { age: 30 } * ``` */ export type UpdateQuery = AnyKeys & _UpdateQuery & AnyObject; /** * A more strict form of UpdateQuery that enforces updating only * known top-level properties. * @example * ```ts * function updateUser(_id: mongoose.Types.ObjectId, update: UpdateQueryKnownOnly) { * return User.updateOne({ _id }, update); * } * ``` */ export type UpdateQueryKnownOnly = _UpdateQuery; export type FlattenMaps = { [K in keyof T]: FlattenProperty; }; export type BufferToBinaryProperty = unknown extends Buffer ? T : T extends Buffer ? mongodb.Binary : T extends Types.DocumentArray ? Types.DocumentArray> : T extends Types.Subdocument ? HydratedSingleSubdocument> : BufferToBinary; /** * Converts any Buffer properties into mongodb.Binary instances, which is what `lean()` returns */ export type BufferToBinary = unknown extends Buffer ? T : T extends Buffer ? mongodb.Binary : T extends Document ? T : T extends TreatAsPrimitives ? T : T extends Record ? { [K in keyof T]: BufferToBinaryProperty } : T; /** * Converts any Buffer properties into { type: 'buffer', data: [1, 2, 3] } format for JSON serialization */ export type BufferToJSON = unknown extends Buffer ? T : T extends Buffer ? { type: 'buffer', data: number[] } : T extends Document ? T : T extends TreatAsPrimitives ? T : T extends Record ? { [K in keyof T]: T[K] extends Buffer ? { type: 'buffer', data: number[] } : T[K] extends Types.DocumentArray ? Types.DocumentArray> : T[K] extends Types.Subdocument ? HydratedSingleSubdocument : BufferToBinary; } : T; /** * Converts any UUID properties into strings for JSON serialization */ export type UUIDToString = T extends Types.UUID ? string : T extends mongodb.UUID ? string : T extends Document ? T : T extends TreatAsPrimitives ? T : T extends Record ? { [K in keyof T]: T[K] extends Types.UUID ? string : T[K] extends mongodb.UUID ? string : T[K] extends Types.DocumentArray ? Types.DocumentArray> : T[K] extends Types.Subdocument ? HydratedSingleSubdocument> : UUIDToString; } : T; /** * Alias for UUIDToString for backwards compatibility. * @deprecated Use UUIDToString instead. */ export type UUIDToJSON = UUIDToString; /** * Converts any ObjectId properties into strings for JSON serialization */ export type ObjectIdToString = T extends mongodb.ObjectId ? string : T extends Document ? T : T extends TreatAsPrimitives ? T : T extends Record ? { [K in keyof T]: T[K] extends mongodb.ObjectId ? string : T[K] extends Types.DocumentArray ? Types.DocumentArray> : T[K] extends Types.Subdocument ? HydratedSingleSubdocument> : ObjectIdToString; } : T; /** * Converts any Date properties into strings for JSON serialization */ export type DateToString = T extends NativeDate ? string : T extends Document ? T : T extends TreatAsPrimitives ? T : T extends Record ? { [K in keyof T]: T[K] extends NativeDate ? string : T[K] extends (NativeDate | null | undefined) ? string | null | undefined : T[K] extends Types.DocumentArray ? Types.DocumentArray> : T[K] extends Types.Subdocument ? HydratedSingleSubdocument> : DateToString; } : T; /** * Converts any Mongoose subdocuments (single nested or doc arrays) into POJO equivalents */ export type SubdocsToPOJOs = T extends Document ? T : T extends TreatAsPrimitives ? T : T extends Record ? { [K in keyof T]: T[K] extends Types.DocumentArray ? ItemType[] : T[K] extends Types.Subdocument ? SubdocType : SubdocsToPOJOs; } : T; export type JSONSerialized = SubdocsToPOJOs< FlattenMaps< BufferToJSON< ObjectIdToString< UUIDToJSON< DateToString > > > > >; /** * Helper types for computing toObject/toJSON return types based on options. * These compose transforms conditionally to avoid combinatorial explosion of overloads. */ type ApplyVirtuals = O extends { virtuals: true } ? T & TVirtuals : T; type GetVersionKeyName = TSchemaOptions extends { versionKey: infer VK } ? VK extends string ? VK : '__v' : '__v'; type ApplyVersionKey = O extends { versionKey: false } ? Omit> : T; /** * Single-pass type that applies all flatten transforms (flattenMaps, flattenObjectIds, flattenUUIDs) * in one recursive traversal. This avoids TypeScript's "union type too complex" error that occurs * when nesting separate recursive transform types. * * By handling all transforms in one pass, we correctly handle ObjectIds/UUIDs nested inside Maps * since we recurse into Map values during the same traversal that converts ObjectIds/UUIDs. */ type ApplyFlattenTransforms = // Handle ObjectId first (before TreatAsPrimitives since ObjectId is in TreatAsPrimitives) T extends mongodb.ObjectId ? O extends { flattenObjectIds: true } ? string : T // Handle UUID (both Types.UUID and mongodb.UUID) : T extends Types.UUID ? O extends { flattenUUIDs: true } ? string : T : T extends mongodb.UUID ? O extends { flattenUUIDs: true } ? string : T // Handle Map - flatten to Record and recurse into values : T extends Map ? O extends { flattenMaps: true } ? Record> : T // Don't recurse into Documents : T extends Document ? T // Don't modify primitives : T extends TreatAsPrimitives ? T // Handle DocumentArray - recurse into items : T extends Types.DocumentArray ? Types.DocumentArray> // Handle plain arrays - recurse into items : T extends Array ? ApplyFlattenTransforms[] // Handle Subdocument - recurse into subdoc type : T extends Types.Subdocument ? HydratedSingleSubdocument> // Handle regular objects - recurse into properties : T extends Record ? { [K in keyof T]: ApplyFlattenTransforms } : T; /** * Computes the return type of toObject/toJSON based on the provided options. * Uses a single-pass transform for flatten operations to correctly handle all combinations. */ export type ToObjectReturnType = ApplyVersionKey< Default__v< ApplyFlattenTransforms< ApplyVirtuals, TVirtuals, O>, O >, TSchemaOptions >, O, TSchemaOptions >; /** * Separate type is needed for properties of union type (for example, Types.DocumentArray | undefined) to apply conditional check to each member of it * https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types */ type FlattenProperty = T extends Map ? Record : T extends TreatAsPrimitives ? T : T extends Document ? T : T extends Types.DocumentArray ? Types.DocumentArray> : FlattenMaps; export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined; export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function | mongodb.Binary | mongodb.ClientSession; export type SchemaDefinitionType = T extends Document ? Omit> : T; /* for ts-mongoose */ export class mquery { } export function overwriteMiddlewareResult(val: any): Kareem.OverwriteMiddlewareResult; export function skipMiddlewareFunction(val: any): Kareem.SkipWrappedFunction; export function overwriteMiddlewareArguments(val: any): Kareem.OverwriteArguments; export default mongoose; }