index.d.ts 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821
  1. declare module 'mongoose' {
  2. import events = require('events');
  3. import mongodb = require('mongodb');
  4. import mongoose = require('mongoose');
  5. import stream = require('stream');
  6. export enum ConnectionStates {
  7. disconnected = 0,
  8. connected = 1,
  9. connecting = 2,
  10. disconnecting = 3,
  11. uninitialized = 99,
  12. }
  13. /** The Mongoose Date [SchemaType](/docs/schematypes.html). */
  14. class NativeDate extends global.Date {}
  15. export type Date = Schema.Types.Date;
  16. /**
  17. * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for
  18. * declaring paths in your schema that should be
  19. * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
  20. * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128`
  21. * instead.
  22. */
  23. export type Decimal128 = Schema.Types.Decimal128;
  24. /**
  25. * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for
  26. * declaring paths in your schema that Mongoose's change tracking, casting,
  27. * and validation should ignore.
  28. */
  29. export type Mixed = Schema.Types.Mixed;
  30. /**
  31. * Mongoose constructor. The exports object of the `mongoose` module is an instance of this
  32. * class. Most apps will only use this one instance.
  33. */
  34. // eslint-disable-next-line @typescript-eslint/ban-types
  35. export const Mongoose: new (options?: object | null) => typeof mongoose;
  36. /**
  37. * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for
  38. * declaring paths in your schema that Mongoose should cast to numbers.
  39. */
  40. export type Number = Schema.Types.Number;
  41. /**
  42. * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for
  43. * declaring paths in your schema that should be
  44. * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/).
  45. * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId`
  46. * instead.
  47. */
  48. export type ObjectId = Schema.Types.ObjectId;
  49. export let Promise: any;
  50. export const PromiseProvider: any;
  51. /** The various Mongoose SchemaTypes. */
  52. export const SchemaTypes: typeof Schema.Types;
  53. /** Expose connection states for user-land */
  54. export const STATES: typeof ConnectionStates;
  55. /** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
  56. export function connect(uri: string, options: ConnectOptions, callback: (err: CallbackError) => void): void;
  57. export function connect(uri: string, callback: (err: CallbackError) => void): void;
  58. export function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
  59. /** The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). */
  60. export const connection: Connection;
  61. /** An array containing all connections associated with this Mongoose instance. */
  62. export const connections: Connection[];
  63. /** An array containing all models associated with this Mongoose instance. */
  64. export const models: { [index: string]: Model<any> };
  65. /** Creates a Connection instance. */
  66. export function createConnection(uri: string, options?: ConnectOptions): Connection & Promise<Connection>;
  67. export function createConnection(): Connection;
  68. export function createConnection(uri: string, options: ConnectOptions, callback: (err: CallbackError, conn: Connection) => void): void;
  69. /**
  70. * Removes the model named `name` from the default connection, if it exists.
  71. * You can use this function to clean up any models you created in your tests to
  72. * prevent OverwriteModelErrors.
  73. */
  74. export function deleteModel(name: string | RegExp): typeof mongoose;
  75. export function disconnect(): Promise<void>;
  76. export function disconnect(cb: (err: CallbackError) => void): void;
  77. /** Gets mongoose options */
  78. export function get(key: string): any;
  79. /**
  80. * Returns true if Mongoose can cast the given value to an ObjectId, or
  81. * false otherwise.
  82. */
  83. export function isValidObjectId(v: any): boolean;
  84. export function model<T>(name: string, schema?: Schema<any>, collection?: string, skipInit?: boolean): Model<T>;
  85. export function model<T, U extends Model<T, TQueryHelpers, any>, TQueryHelpers = {}>(
  86. name: string,
  87. schema?: Schema<T, U>,
  88. collection?: string,
  89. skipInit?: boolean
  90. ): U;
  91. /** Returns an array of model names created on this instance of Mongoose. */
  92. export function modelNames(): Array<string>;
  93. /** The node-mongodb-native driver Mongoose uses. */
  94. export const mongo: typeof mongodb;
  95. /**
  96. * Mongoose uses this function to get the current time when setting
  97. * [timestamps](/docs/guide.html#timestamps). You may stub out this function
  98. * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing.
  99. */
  100. export function now(): Date;
  101. /** Declares a global plugin executed on all Schemas. */
  102. export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): typeof mongoose;
  103. /** Getter/setter around function for pluralizing collection names. */
  104. export function pluralize(fn?: ((str: string) => string) | null): ((str: string) => string) | null;
  105. /** Sets mongoose options */
  106. export function set(key: string, value: any): void;
  107. /**
  108. * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
  109. * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
  110. * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
  111. */
  112. export function startSession(options?: mongodb.SessionOptions): Promise<mongodb.ClientSession>;
  113. export function startSession(options: mongodb.SessionOptions, cb: (err: any, session: mongodb.ClientSession) => void): void;
  114. /** The Mongoose version */
  115. export const version: string;
  116. export type CastError = Error.CastError;
  117. type Mongoose = typeof mongoose;
  118. // eslint-disable-next-line @typescript-eslint/no-empty-interface
  119. interface ClientSession extends mongodb.ClientSession { }
  120. interface ConnectOptions extends mongodb.MongoClientOptions {
  121. /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
  122. bufferCommands?: boolean;
  123. /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
  124. dbName?: string;
  125. /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
  126. user?: string;
  127. /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
  128. pass?: string;
  129. /** Set to false to disable automatic index creation for all models associated with this connection. */
  130. autoIndex?: boolean;
  131. /** True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. */
  132. useFindAndModify?: boolean;
  133. /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
  134. autoCreate?: boolean;
  135. /** False by default. If `true`, this connection will use `createIndex()` instead of `ensureIndex()` for automatic index builds via `Model.init()`. */
  136. useCreateIndex?: boolean;
  137. }
  138. class Connection extends events.EventEmitter {
  139. /** Closes the connection */
  140. close(callback: (err: CallbackError) => void): void;
  141. close(force: boolean, callback: (err: CallbackError) => void): void;
  142. close(force?: boolean): Promise<void>;
  143. /** Retrieves a collection, creating it if not cached. */
  144. collection(name: string, options?: mongodb.CollectionCreateOptions): Collection;
  145. /** A hash of the collections associated with this connection */
  146. collections: { [index: string]: Collection };
  147. /** A hash of the global options that are associated with this connection */
  148. config: any;
  149. /** The mongodb.Db instance, set when the connection is opened */
  150. db: mongodb.Db;
  151. /**
  152. * Helper for `createCollection()`. Will explicitly create the given collection
  153. * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/)
  154. * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
  155. */
  156. createCollection<T = any>(name: string, options?: mongodb.CollectionCreateOptions): Promise<mongodb.Collection<T>>;
  157. createCollection<T = any>(name: string, cb: (err: CallbackError, collection: mongodb.Collection<T>) => void): void;
  158. createCollection<T = any>(name: string, options: mongodb.CollectionCreateOptions, cb?: (err: CallbackError, collection: mongodb.Collection) => void): Promise<mongodb.Collection<T>>;
  159. /**
  160. * Removes the model named `name` from this connection, if it exists. You can
  161. * use this function to clean up any models you created in your tests to
  162. * prevent OverwriteModelErrors.
  163. */
  164. deleteModel(name: string): this;
  165. /**
  166. * Helper for `dropCollection()`. Will delete the given collection, including
  167. * all documents and indexes.
  168. */
  169. dropCollection(collection: string): Promise<void>;
  170. dropCollection(collection: string, cb: (err: CallbackError) => void): void;
  171. /**
  172. * Helper for `dropDatabase()`. Deletes the given database, including all
  173. * collections, documents, and indexes.
  174. */
  175. dropDatabase(): Promise<void>;
  176. dropDatabase(cb: (err: CallbackError) => void): void;
  177. /** Gets the value of the option `key`. Equivalent to `conn.options[key]` */
  178. get(key: string): any;
  179. /**
  180. * Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
  181. * that this connection uses to talk to MongoDB.
  182. */
  183. getClient(): mongodb.MongoClient;
  184. /**
  185. * The host name portion of the URI. If multiple hosts, such as a replica set,
  186. * this will contain the first host name in the URI
  187. */
  188. host: string;
  189. /**
  190. * A number identifier for this connection. Used for debugging when
  191. * you have [multiple connections](/docs/connections.html#multiple_connections).
  192. */
  193. id: number;
  194. /**
  195. * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
  196. * a map from model names to models. Contains all models that have been
  197. * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model).
  198. */
  199. models: { [index: string]: Model<any> };
  200. /** Defines or retrieves a model. */
  201. model<T>(name: string, schema?: Schema<T>, collection?: string): Model<T>;
  202. model<T, U extends Model<T, TQueryHelpers, any>, TQueryHelpers = {}>(
  203. name: string,
  204. schema?: Schema<T, U, TQueryHelpers>,
  205. collection?: string,
  206. skipInit?: boolean
  207. ): U;
  208. /** Returns an array of model names created on this connection. */
  209. modelNames(): Array<string>;
  210. /** The name of the database this connection points to. */
  211. name: string;
  212. /** Opens the connection with a URI using `MongoClient.connect()`. */
  213. openUri(uri: string, options?: ConnectOptions): Promise<Connection>;
  214. openUri(uri: string, callback: (err: CallbackError, conn?: Connection) => void): Connection;
  215. openUri(uri: string, options: ConnectOptions, callback: (err: CallbackError, conn?: Connection) => void): Connection;
  216. /** The password specified in the URI */
  217. pass: string;
  218. /**
  219. * The port portion of the URI. If multiple hosts, such as a replica set,
  220. * this will contain the port from the first host name in the URI.
  221. */
  222. port: number;
  223. /** Declares a plugin executed on all schemas you pass to `conn.model()` */
  224. plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Connection;
  225. /** The plugins that will be applied to all models created on this connection. */
  226. plugins: Array<any>;
  227. /**
  228. * Connection ready state
  229. *
  230. * - 0 = disconnected
  231. * - 1 = connected
  232. * - 2 = connecting
  233. * - 3 = disconnecting
  234. */
  235. readyState: number;
  236. /** Sets the value of the option `key`. Equivalent to `conn.options[key] = val` */
  237. set(key: string, value: any): any;
  238. /**
  239. * Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
  240. * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
  241. * reuse it.
  242. */
  243. setClient(client: mongodb.MongoClient): this;
  244. /**
  245. * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
  246. * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
  247. * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
  248. */
  249. startSession(options?: mongodb.SessionOptions): Promise<mongodb.ClientSession>;
  250. startSession(options: mongodb.SessionOptions, cb: (err: any, session: mongodb.ClientSession) => void): void;
  251. /**
  252. * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
  253. * in a transaction. Mongoose will commit the transaction if the
  254. * async function executes successfully and attempt to retry if
  255. * there was a retriable error.
  256. */
  257. transaction(fn: (session: mongodb.ClientSession) => Promise<any>): Promise<any>;
  258. /** Switches to a different database using the same connection pool. */
  259. useDb(name: string, options?: { useCache?: boolean, noListener?: boolean }): Connection;
  260. /** The username specified in the URI */
  261. user: string;
  262. /** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model.watch). */
  263. watch(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream;
  264. }
  265. /*
  266. * section collection.js
  267. * http://mongoosejs.com/docs/api.html#collection-js
  268. */
  269. interface CollectionBase extends mongodb.Collection {
  270. /*
  271. * Abstract methods. Some of these are already defined on the
  272. * mongodb.Collection interface so they've been commented out.
  273. */
  274. ensureIndex(...args: any[]): any;
  275. findAndModify(...args: any[]): any;
  276. getIndexes(...args: any[]): any;
  277. /** The collection name */
  278. collectionName: string;
  279. /** The Connection instance */
  280. conn: Connection;
  281. /** The collection name */
  282. name: string;
  283. }
  284. /*
  285. * section drivers/node-mongodb-native/collection.js
  286. * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js
  287. */
  288. let Collection: Collection;
  289. interface Collection extends CollectionBase {
  290. /**
  291. * Collection constructor
  292. * @param name name of the collection
  293. * @param conn A MongooseConnection instance
  294. * @param opts optional collection options
  295. */
  296. // eslint-disable-next-line @typescript-eslint/no-misused-new
  297. new(name: string, conn: Connection, opts?: any): Collection;
  298. /** Formatter for debug print args */
  299. $format(arg: any): string;
  300. /** Debug print helper */
  301. $print(name: any, i: any, args: any[]): void;
  302. /** Retrieves information about this collections indexes. */
  303. getIndexes(): any;
  304. }
  305. class Document<T = any, TQueryHelpers = any> {
  306. constructor(doc?: T | any);
  307. /** This documents _id. */
  308. _id?: T;
  309. /** This documents __v. */
  310. __v?: any;
  311. /* Get all subdocs (by bfs) */
  312. $getAllSubdocs(): Document[];
  313. /** Don't run validation on this path or persist changes to this path. */
  314. $ignore(path: string): void;
  315. /** Checks if a path is set to its default. */
  316. $isDefault(path: string): boolean;
  317. /** Getter/setter, determines whether the document was removed or not. */
  318. $isDeleted(val?: boolean): boolean;
  319. /** Returns an array of all populated documents associated with the query */
  320. $getPopulatedDocs(): Document[];
  321. /**
  322. * Returns true if the given path is nullish or only contains empty objects.
  323. * Useful for determining whether this subdoc will get stripped out by the
  324. * [minimize option](/docs/guide.html#minimize).
  325. */
  326. $isEmpty(path: string): boolean;
  327. /** Checks if a path is invalid */
  328. $isValid(path: string): boolean;
  329. /**
  330. * Empty object that you can use for storing properties on the document. This
  331. * is handy for passing data to middleware without conflicting with Mongoose
  332. * internals.
  333. */
  334. $locals: Record<string, unknown>;
  335. /** Marks a path as valid, removing existing validation errors. */
  336. $markValid(path: string): void;
  337. /**
  338. * A string containing the current operation that Mongoose is executing
  339. * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`.
  340. */
  341. $op: string | null;
  342. /**
  343. * Getter/setter around the session associated with this document. Used to
  344. * automatically set `session` if you `save()` a doc that you got from a
  345. * query with an associated session.
  346. */
  347. $session(session?: mongodb.ClientSession | null): mongodb.ClientSession;
  348. /** Alias for `set()`, used internally to avoid conflicts */
  349. $set(path: string, val: any, options?: any): this;
  350. $set(path: string, val: any, type: any, options?: any): this;
  351. $set(value: any): this;
  352. /** Additional properties to attach to the query when calling `save()` and `isNew` is false. */
  353. $where: Record<string, unknown>;
  354. /** If this is a discriminator model, `baseModelName` is the name of the base model. */
  355. baseModelName?: string;
  356. /** Collection the model uses. */
  357. collection: Collection;
  358. /** Connection the model uses. */
  359. db: Connection;
  360. /** Removes this document from the db. */
  361. delete(options?: QueryOptions): QueryWithHelpers<any, this, TQueryHelpers>;
  362. delete(options: QueryOptions, cb?: (err: CallbackError, res: any) => void): void;
  363. delete(cb: (err: CallbackError, res: any) => void): void;
  364. /** Removes this document from the db. */
  365. deleteOne(options?: QueryOptions): QueryWithHelpers<any, this, TQueryHelpers>;
  366. deleteOne(options: QueryOptions, cb?: (err: CallbackError, res: any) => void): void;
  367. deleteOne(cb: (err: CallbackError, res: any) => void): void;
  368. /** Takes a populated field and returns it to its unpopulated state. */
  369. depopulate(path: string): this;
  370. /**
  371. * Returns the list of paths that have been directly modified. A direct
  372. * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`,
  373. * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`.
  374. */
  375. directModifiedPaths(): Array<string>;
  376. /**
  377. * Returns true if this document is equal to another document.
  378. *
  379. * Documents are considered equal when they have matching `_id`s, unless neither
  380. * document has an `_id`, in which case this function falls back to using
  381. * `deepEqual()`.
  382. */
  383. equals(doc: Document<T>): boolean;
  384. /** Hash containing current validation errors. */
  385. errors?: Error.ValidationError;
  386. /** Explicitly executes population and returns a promise. Useful for promises integration. */
  387. execPopulate(): Promise<this>;
  388. execPopulate(callback: (err: CallbackError, res: this) => void): void;
  389. /** Returns the value of a path. */
  390. get(path: string, type?: any, options?: any): any;
  391. /**
  392. * Returns the changes that happened to the document
  393. * in the format that will be sent to MongoDB.
  394. */
  395. getChanges(): UpdateQuery<this>;
  396. /** The string version of this documents _id. */
  397. id?: any;
  398. /** Signal that we desire an increment of this documents version. */
  399. increment(): this;
  400. /**
  401. * Initializes the document without setters or marking anything modified.
  402. * Called internally after a document is returned from mongodb. Normally,
  403. * you do **not** need to call this function on your own.
  404. */
  405. init(obj: any, opts?: any, cb?: (err: CallbackError, doc: this) => void): this;
  406. /** Marks a path as invalid, causing validation to fail. */
  407. invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null;
  408. /** Returns true if `path` was directly set and modified, else false. */
  409. isDirectModified(path: string): boolean;
  410. /** Checks if `path` was explicitly selected. If no projection, always returns true. */
  411. isDirectSelected(path: string): boolean;
  412. /** Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. */
  413. isInit(path: string): boolean;
  414. /**
  415. * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path
  416. * in this document is modified.
  417. */
  418. isModified(path?: string | Array<string>): boolean;
  419. /** Boolean flag specifying if the document is new. */
  420. isNew: boolean;
  421. /** Checks if `path` was selected in the source query which initialized this document. */
  422. isSelected(path: string): boolean;
  423. /** Marks the path as having pending changes to write to the db. */
  424. markModified(path: string, scope?: any): void;
  425. /** Returns the list of paths that have been modified. */
  426. modifiedPaths(options?: { includeChildren?: boolean }): Array<string>;
  427. /** Returns another Model instance. */
  428. model<T extends Model<any>>(name: string): T;
  429. /** The name of the model */
  430. modelName: string;
  431. /**
  432. * Overwrite all values in this document with the values of `obj`, except
  433. * for immutable properties. Behaves similarly to `set()`, except for it
  434. * unsets all properties that aren't in `obj`.
  435. */
  436. overwrite(obj: DocumentDefinition<this>): this;
  437. /**
  438. * If this document is a subdocument or populated document, returns the
  439. * document's parent. Returns undefined otherwise.
  440. */
  441. $parent(): Document | undefined;
  442. /**
  443. * Populates document references, executing the `callback` when complete.
  444. * If you want to use promises instead, use this function with
  445. * [`execPopulate()`](#document_Document-execPopulate).
  446. */
  447. populate(path: string, callback?: (err: CallbackError, res: this) => void): this;
  448. populate(path: string, names: string, callback?: (err: any, res: this) => void): this;
  449. populate(opts: PopulateOptions | Array<PopulateOptions>, callback?: (err: CallbackError, res: this) => void): this;
  450. /** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */
  451. populated(path: string): any;
  452. /** Removes this document from the db. */
  453. remove(options?: QueryOptions): Promise<this>;
  454. remove(options?: QueryOptions, cb?: (err: CallbackError, res: any) => void): void;
  455. /** Sends a replaceOne command with this document `_id` as the query selector. */
  456. replaceOne(replacement?: DocumentDefinition<this>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): Query<any, this>;
  457. /** Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. */
  458. save(options?: SaveOptions): Promise<this>;
  459. save(options?: SaveOptions, fn?: (err: CallbackError, doc: this) => void): void;
  460. save(fn?: (err: CallbackError, doc: this) => void): void;
  461. /** The document's schema. */
  462. schema: Schema;
  463. /** Sets the value of a path, or many paths. */
  464. set(path: string, val: any, options?: any): this;
  465. set(path: string, val: any, type: any, options?: any): this;
  466. set(value: any): this;
  467. /** The return value of this method is used in calls to JSON.stringify(doc). */
  468. toJSON(options?: ToObjectOptions): LeanDocument<this>;
  469. toJSON<T>(options?: ToObjectOptions): T;
  470. /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
  471. toObject(options?: ToObjectOptions): LeanDocument<this>;
  472. toObject<T>(options?: ToObjectOptions): T;
  473. /** Clears the modified state on the specified path. */
  474. unmarkModified(path: string): void;
  475. /** Sends an update command with this document `_id` as the query selector. */
  476. update(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: CallbackError, res: any) => void): Query<any, this>;
  477. /** Sends an updateOne command with this document `_id` as the query selector. */
  478. updateOne(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: CallbackError, res: any) => void): Query<any, this>;
  479. /** Executes registered validation rules for this document. */
  480. validate(pathsToValidate?: Array<string>, options?: any): Promise<void>;
  481. validate(callback: (err: CallbackError) => void): void;
  482. validate(pathsToValidate: Array<string>, callback: (err: CallbackError) => void): void;
  483. validate(pathsToValidate: Array<string>, options: any, callback: (err: CallbackError) => void): void;
  484. /** Executes registered validation rules (skipping asynchronous validators) for this document. */
  485. validateSync(pathsToValidate?: Array<string>, options?: any): Error.ValidationError | null;
  486. }
  487. interface AcceptsDiscriminator {
  488. /** Adds a discriminator type. */
  489. discriminator<D extends Document>(name: string | number, schema: Schema<D>, value?: string | number | ObjectId): Model<D>;
  490. discriminator<T extends Document, U extends Model<T>>(name: string | number, schema: Schema<T, U>, value?: string | number | ObjectId): U;
  491. }
  492. interface AnyObject { [k: string]: any }
  493. type EnforceDocument<T, TMethods> = T extends Document ? T : T & Document & TMethods;
  494. export const Model: Model<any>;
  495. // eslint-disable-next-line no-undef
  496. interface Model<T, TQueryHelpers = {}, TMethods = {}> extends NodeJS.EventEmitter, AcceptsDiscriminator {
  497. new(doc?: T | any): EnforceDocument<T, TMethods>;
  498. aggregate<R = any>(pipeline?: any[]): Aggregate<Array<R>>;
  499. // eslint-disable-next-line @typescript-eslint/ban-types
  500. aggregate<R = any>(pipeline: any[], cb: Function): Promise<Array<R>>;
  501. /** Base Mongoose instance the model uses. */
  502. base: typeof mongoose;
  503. /**
  504. * If this is a discriminator model, `baseModelName` is the name of
  505. * the base model.
  506. */
  507. baseModelName: string | undefined;
  508. /**
  509. * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`,
  510. * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one
  511. * command. This is faster than sending multiple independent operations (e.g.
  512. * if you use `create()`) because with `bulkWrite()` there is only one round
  513. * trip to MongoDB.
  514. */
  515. bulkWrite(writes: Array<any>, options?: mongodb.CollectionBulkWriteOptions): Promise<mongodb.BulkWriteOpResultObject>;
  516. bulkWrite(writes: Array<any>, options?: mongodb.CollectionBulkWriteOptions, cb?: (err: any, res: mongodb.BulkWriteOpResultObject) => void): void;
  517. /** Collection the model uses. */
  518. collection: Collection;
  519. /** Creates a `count` query: counts the number of documents that match `filter`. */
  520. count(callback?: (err: any, count: number) => void): QueryWithHelpers<number, EnforceDocument<T, TMethods>, TQueryHelpers>;
  521. count(filter: FilterQuery<T>, callback?: (err: any, count: number) => void): QueryWithHelpers<number, EnforceDocument<T, TMethods>, TQueryHelpers>;
  522. /** Creates a `countDocuments` query: counts the number of documents that match `filter`. */
  523. countDocuments(callback?: (err: any, count: number) => void): QueryWithHelpers<number, EnforceDocument<T, TMethods>, TQueryHelpers>;
  524. countDocuments(filter: FilterQuery<T>, callback?: (err: any, count: number) => void): QueryWithHelpers<number, EnforceDocument<T, TMethods>, TQueryHelpers>;
  525. /** Creates a new document or documents */
  526. create(docs: (T | DocumentDefinition<T> | AnyObject)[], options?: SaveOptions): Promise<EnforceDocument<T, TMethods>[]>;
  527. create(docs: (T | DocumentDefinition<T> | AnyObject)[], callback: (err: CallbackError, docs: EnforceDocument<T, TMethods>[]) => void): void;
  528. create(doc: T | DocumentDefinition<T> | AnyObject): Promise<EnforceDocument<T, TMethods>>;
  529. create(doc: T | DocumentDefinition<T> | AnyObject, callback: (err: CallbackError, doc: EnforceDocument<T, TMethods>) => void): void;
  530. create<DocContents = T | DocumentDefinition<T>>(docs: DocContents[], options?: SaveOptions): Promise<EnforceDocument<T, TMethods>[]>;
  531. create<DocContents = T | DocumentDefinition<T>>(docs: DocContents[], callback: (err: CallbackError, docs: EnforceDocument<T, TMethods>[]) => void): void;
  532. create<DocContents = T | DocumentDefinition<T>>(doc: DocContents): Promise<EnforceDocument<T, TMethods>>;
  533. create<DocContents = T | DocumentDefinition<T>>(...docs: DocContents[]): Promise<EnforceDocument<T, TMethods>[]>;
  534. create<DocContents = T | DocumentDefinition<T>>(doc: DocContents, callback: (err: CallbackError, doc: EnforceDocument<T, TMethods>) => void): void;
  535. /**
  536. * Create the collection for this model. By default, if no indexes are specified,
  537. * mongoose will not create the collection for the model until any documents are
  538. * created. Use this method to create the collection explicitly.
  539. */
  540. createCollection(options?: mongodb.CollectionCreateOptions): Promise<mongodb.Collection<EnforceDocument<T, TMethods>>>;
  541. createCollection(options: mongodb.CollectionCreateOptions | null, callback: (err: CallbackError, collection: mongodb.Collection<EnforceDocument<T, TMethods>>) => void): void;
  542. /**
  543. * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)
  544. * function.
  545. */
  546. createIndexes(callback?: (err: any) => void): Promise<void>;
  547. createIndexes(options?: any, callback?: (err: any) => void): Promise<void>;
  548. /** Connection the model uses. */
  549. db: Connection;
  550. /**
  551. * Deletes all of the documents that match `conditions` from the collection.
  552. * Behaves like `remove()`, but deletes all documents that match `conditions`
  553. * regardless of the `single` option.
  554. */
  555. deleteMany(filter?: FilterQuery<T>, options?: QueryOptions, callback?: (err: CallbackError) => void): QueryWithHelpers<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }, EnforceDocument<T, TMethods>, TQueryHelpers>;
  556. deleteMany(filter: FilterQuery<T>, callback: (err: CallbackError) => void): QueryWithHelpers<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }, EnforceDocument<T, TMethods>, TQueryHelpers>;
  557. deleteMany(callback: (err: CallbackError) => void): QueryWithHelpers<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }, EnforceDocument<T, TMethods>, TQueryHelpers>;
  558. /**
  559. * Deletes the first document that matches `conditions` from the collection.
  560. * Behaves like `remove()`, but deletes at most one document regardless of the
  561. * `single` option.
  562. */
  563. deleteOne(filter?: FilterQuery<T>, options?: QueryOptions, callback?: (err: CallbackError) => void): QueryWithHelpers<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }, EnforceDocument<T, TMethods>, TQueryHelpers>;
  564. deleteOne(filter: FilterQuery<T>, callback: (err: CallbackError) => void): QueryWithHelpers<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }, EnforceDocument<T, TMethods>, TQueryHelpers>;
  565. deleteOne(callback: (err: CallbackError) => void): QueryWithHelpers<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }, EnforceDocument<T, TMethods>, TQueryHelpers>;
  566. /**
  567. * Sends `createIndex` commands to mongo for each index declared in the schema.
  568. * The `createIndex` commands are sent in series.
  569. */
  570. ensureIndexes(callback?: (err: any) => void): Promise<void>;
  571. ensureIndexes(options?: any, callback?: (err: any) => void): Promise<void>;
  572. /**
  573. * Event emitter that reports any errors that occurred. Useful for global error
  574. * handling.
  575. */
  576. // eslint-disable-next-line no-undef
  577. events: NodeJS.EventEmitter;
  578. /**
  579. * Finds a single document by its _id field. `findById(id)` is almost*
  580. * equivalent to `findOne({ _id: id })`. If you want to query by a document's
  581. * `_id`, use `findById()` instead of `findOne()`.
  582. */
  583. findById(id: any, projection?: any | null, options?: QueryOptions | null, callback?: (err: CallbackError, doc: EnforceDocument<T, TMethods> | null) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  584. /** Finds one document. */
  585. findOne(filter?: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: (err: CallbackError, doc: EnforceDocument<T, TMethods> | null) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  586. /**
  587. * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
  588. * The document returned has no paths marked as modified initially.
  589. */
  590. hydrate(obj: any): EnforceDocument<T, TMethods>;
  591. /**
  592. * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/),
  593. * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off.
  594. * Mongoose calls this function automatically when a model is created using
  595. * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or
  596. * [`connection.model()`](/docs/api.html#connection_Connection-model), so you
  597. * don't need to call it.
  598. */
  599. init(callback?: (err: any) => void): Promise<EnforceDocument<T, TMethods>>;
  600. /** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */
  601. insertMany(docs: Array<T | DocumentDefinition<T> | AnyObject>, options: InsertManyOptions & { rawResult: true }): Promise<InsertManyResult>;
  602. insertMany(docs: Array<T | DocumentDefinition<T> | AnyObject>, options?: InsertManyOptions): Promise<Array<EnforceDocument<T, TMethods>>>;
  603. insertMany(doc: T | DocumentDefinition<T> | AnyObject, options: InsertManyOptions & { rawResult: true }): Promise<InsertManyResult>;
  604. insertMany(doc: T | DocumentDefinition<T> | AnyObject, options?: InsertManyOptions): Promise<EnforceDocument<T, TMethods>>;
  605. insertMany(doc: T | DocumentDefinition<T> | AnyObject, options?: InsertManyOptions, callback?: (err: CallbackError, res: EnforceDocument<T, TMethods> | InsertManyResult) => void): void;
  606. insertMany(docs: Array<T | DocumentDefinition<T> | AnyObject>, options?: InsertManyOptions, callback?: (err: CallbackError, res: Array<EnforceDocument<T, TMethods>> | InsertManyResult) => void): void;
  607. /**
  608. * Lists the indexes currently defined in MongoDB. This may or may not be
  609. * the same as the indexes defined in your schema depending on whether you
  610. * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you
  611. * build indexes manually.
  612. */
  613. listIndexes(callback: (err: CallbackError, res: Array<any>) => void): void;
  614. listIndexes(): Promise<Array<any>>;
  615. /** The name of the model */
  616. modelName: string;
  617. /** Populates document references. */
  618. populate(docs: Array<any>, options: PopulateOptions | Array<PopulateOptions> | string,
  619. callback?: (err: any, res: (EnforceDocument<T, TMethods>)[]) => void): Promise<Array<EnforceDocument<T, TMethods>>>;
  620. populate(doc: any, options: PopulateOptions | Array<PopulateOptions> | string,
  621. callback?: (err: any, res: EnforceDocument<T, TMethods>) => void): Promise<EnforceDocument<T, TMethods>>;
  622. /**
  623. * Makes the indexes in MongoDB match the indexes defined in this model's
  624. * schema. This function will drop any indexes that are not defined in
  625. * the model's schema except the `_id` index, and build any indexes that
  626. * are in your schema but not in MongoDB.
  627. */
  628. syncIndexes(options?: Record<string, unknown>): Promise<Array<string>>;
  629. syncIndexes(options: Record<string, unknown> | null, callback: (err: CallbackError, dropped: Array<string>) => void): void;
  630. /**
  631. * Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
  632. * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
  633. * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
  634. * */
  635. startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise<mongodb.ClientSession>;
  636. /** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */
  637. validate(callback?: (err: any) => void): Promise<void>;
  638. validate(optional: any, callback?: (err: any) => void): Promise<void>;
  639. validate(optional: any, pathsToValidate: string[], callback?: (err: any) => void): Promise<void>;
  640. /** Watches the underlying collection for changes using [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). */
  641. watch(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream;
  642. /** Adds a `$where` clause to this query */
  643. // eslint-disable-next-line @typescript-eslint/ban-types
  644. $where(argument: string | Function): QueryWithHelpers<Array<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  645. /** Registered discriminators for this model. */
  646. discriminators: { [name: string]: Model<any> } | undefined;
  647. /** Translate any aliases fields/conditions so the final query or document object is pure */
  648. translateAliases(raw: any): any;
  649. /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
  650. distinct(field: string, filter?: FilterQuery<T>, callback?: (err: any, count: number) => void): QueryWithHelpers<Array<any>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  651. /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
  652. estimatedDocumentCount(options?: QueryOptions, callback?: (err: any, count: number) => void): QueryWithHelpers<number, EnforceDocument<T, TMethods>, TQueryHelpers>;
  653. /**
  654. * Returns true if at least one document exists in the database that matches
  655. * the given `filter`, and false otherwise.
  656. */
  657. exists(filter: FilterQuery<T>): Promise<boolean>;
  658. exists(filter: FilterQuery<T>, callback: (err: any, res: boolean) => void): void;
  659. /** Creates a `find` query: gets a list of documents that match `filter`. */
  660. find(callback?: (err: any, docs: EnforceDocument<T, TMethods>[]) => void): QueryWithHelpers<Array<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  661. find(filter: FilterQuery<T>, callback?: (err: any, docs: T[]) => void): QueryWithHelpers<Array<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  662. find(filter: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: (err: any, docs: EnforceDocument<T, TMethods>[]) => void): QueryWithHelpers<Array<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  663. /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
  664. findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: any, doc: EnforceDocument<T, TMethods> | null, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  665. /** Creates a `findByIdAndRemove` query, filtering by the given `_id`. */
  666. findByIdAndRemove(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: any, doc: EnforceDocument<T, TMethods> | null, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  667. /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
  668. findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<T> | UpdateWithAggregationPipeline, options: QueryOptions & { rawResult: true }, callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<EnforceDocument<T, TMethods>>, res: any) => void): QueryWithHelpers<mongodb.FindAndModifyWriteOpResultObject<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  669. findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<T> | UpdateWithAggregationPipeline, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: any, doc: EnforceDocument<T, TMethods>, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  670. findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<T> | UpdateWithAggregationPipeline, callback?: (err: any, doc: T | null, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  671. findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: any, doc: EnforceDocument<T, TMethods> | null, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  672. /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
  673. findOneAndDelete(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: any, doc: EnforceDocument<T, TMethods> | null, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  674. /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
  675. findOneAndRemove(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: any, doc: EnforceDocument<T, TMethods> | null, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  676. /** Creates a `findOneAndReplace` query: atomically finds the given document and replaces it with `replacement`. */
  677. findOneAndReplace(filter: FilterQuery<T>, replacement: DocumentDefinition<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: any, doc: EnforceDocument<T, TMethods>, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  678. findOneAndReplace(filter?: FilterQuery<T>, replacement?: DocumentDefinition<T>, options?: QueryOptions | null, callback?: (err: any, doc: EnforceDocument<T, TMethods> | null, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  679. /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
  680. findOneAndUpdate(filter: FilterQuery<T>, update: UpdateQuery<T> | UpdateWithAggregationPipeline, options: QueryOptions & { rawResult: true }, callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<EnforceDocument<T, TMethods>>, res: any) => void): QueryWithHelpers<mongodb.FindAndModifyWriteOpResultObject<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  681. findOneAndUpdate(filter: FilterQuery<T>, update: UpdateQuery<T> | UpdateWithAggregationPipeline, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: any, doc: EnforceDocument<T, TMethods>, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  682. findOneAndUpdate(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: any, doc: EnforceDocument<T, TMethods> | null, res: any) => void): QueryWithHelpers<EnforceDocument<T, TMethods> | null, EnforceDocument<T, TMethods>, TQueryHelpers>;
  683. geoSearch(filter?: FilterQuery<T>, options?: GeoSearchOptions, callback?: (err: CallbackError, res: Array<EnforceDocument<T, TMethods>>) => void): QueryWithHelpers<Array<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  684. /** Executes a mapReduce command. */
  685. mapReduce<Key, Value>(
  686. o: MapReduceOptions<T, Key, Value>,
  687. callback?: (err: any, res: any) => void
  688. ): Promise<any>;
  689. remove(filter?: any, callback?: (err: CallbackError) => void): QueryWithHelpers<any, EnforceDocument<T, TMethods>, TQueryHelpers>;
  690. /** Creates a `replaceOne` query: finds the first document that matches `filter` and replaces it with `replacement`. */
  691. replaceOne(filter?: FilterQuery<T>, replacement?: DocumentDefinition<T>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<any, EnforceDocument<T, TMethods>, TQueryHelpers>;
  692. /** Schema the model uses. */
  693. schema: Schema;
  694. /**
  695. * @deprecated use `updateOne` or `updateMany` instead.
  696. * Creates a `update` query: updates one or many documents that match `filter` with `update`, based on the `multi` option.
  697. */
  698. update(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<UpdateWriteOpResult, EnforceDocument<T, TMethods>, TQueryHelpers>;
  699. /** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */
  700. updateMany(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<UpdateWriteOpResult, EnforceDocument<T, TMethods>, TQueryHelpers>;
  701. /** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */
  702. updateOne(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<UpdateWriteOpResult, EnforceDocument<T, TMethods>, TQueryHelpers>;
  703. /** Creates a Query, applies the passed conditions, and returns the Query. */
  704. where(path: string, val?: any): QueryWithHelpers<Array<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  705. where(obj: object): QueryWithHelpers<Array<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  706. where(): QueryWithHelpers<Array<EnforceDocument<T, TMethods>>, EnforceDocument<T, TMethods>, TQueryHelpers>;
  707. }
  708. type _UpdateWriteOpResult = mongodb.UpdateWriteOpResult['result'];
  709. interface UpdateWriteOpResult extends _UpdateWriteOpResult {
  710. upserted?: Array<{index: number, _id: any}>;
  711. }
  712. interface QueryOptions {
  713. arrayFilters?: { [key: string]: any }[];
  714. batchSize?: number;
  715. collation?: mongodb.CollationDocument;
  716. comment?: any;
  717. context?: string;
  718. explain?: any;
  719. fields?: any | string;
  720. hint?: any;
  721. /**
  722. * If truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document.
  723. */
  724. lean?: boolean | any;
  725. limit?: number;
  726. maxTimeMS?: number;
  727. maxscan?: number;
  728. multi?: boolean;
  729. multipleCastError?: boolean;
  730. /**
  731. * By default, `findOneAndUpdate()` returns the document as it was **before**
  732. * `update` was applied. If you set `new: true`, `findOneAndUpdate()` will
  733. * instead give you the object after `update` was applied.
  734. */
  735. new?: boolean;
  736. omitUndefined?: boolean;
  737. overwrite?: boolean;
  738. overwriteDiscriminatorKey?: boolean;
  739. populate?: string;
  740. projection?: any;
  741. /**
  742. * if true, returns the raw result from the MongoDB driver
  743. */
  744. rawResult?: boolean;
  745. readPreference?: mongodb.ReadPreferenceMode;
  746. /**
  747. * An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`.
  748. */
  749. returnOriginal?: boolean;
  750. /**
  751. * Another alias for the `new` option. `returnOriginal` is deprecated so this should be used.
  752. */
  753. returnDocument?: string;
  754. runValidators?: boolean;
  755. /** The session associated with this query. */
  756. session?: mongodb.ClientSession;
  757. setDefaultsOnInsert?: boolean;
  758. skip?: number;
  759. snapshot?: any;
  760. sort?: any;
  761. /** overwrites the schema's strict mode option */
  762. strict?: boolean | string;
  763. tailable?: number;
  764. /**
  765. * If set to `false` and schema-level timestamps are enabled,
  766. * skip timestamps for this update. Note that this allows you to overwrite
  767. * timestamps. Does nothing if schema-level timestamps are not set.
  768. */
  769. timestamps?: boolean;
  770. upsert?: boolean;
  771. useFindAndModify?: boolean;
  772. writeConcern?: any;
  773. }
  774. type MongooseQueryOptions = Pick<QueryOptions, 'populate' | 'lean' | 'omitUndefined' | 'strict' | 'useFindAndModify'>;
  775. interface SaveOptions {
  776. checkKeys?: boolean;
  777. j?: boolean;
  778. safe?: boolean | WriteConcern;
  779. session?: ClientSession | null;
  780. timestamps?: boolean;
  781. validateBeforeSave?: boolean;
  782. validateModifiedOnly?: boolean;
  783. w?: number | string;
  784. wtimeout?: number;
  785. }
  786. interface WriteConcern {
  787. j?: boolean;
  788. w?: number | 'majority' | TagSet;
  789. wtimeout?: number;
  790. }
  791. interface TagSet {
  792. [k: string]: string;
  793. }
  794. interface InsertManyOptions {
  795. limit?: number;
  796. rawResult?: boolean;
  797. ordered?: boolean;
  798. lean?: boolean;
  799. session?: mongodb.ClientSession;
  800. populate?: string | string[] | PopulateOptions | PopulateOptions[];
  801. }
  802. interface InsertManyResult extends mongodb.InsertWriteOpResult<any> {
  803. mongoose?: { validationErrors?: Array<Error.CastError | Error.ValidatorError> }
  804. }
  805. interface MapReduceOptions<T, Key, Val> {
  806. // eslint-disable-next-line @typescript-eslint/ban-types
  807. map: Function | string;
  808. reduce: (key: Key, vals: T[]) => Val;
  809. /** query filter object. */
  810. query?: any;
  811. /** sort input objects using this key */
  812. sort?: any;
  813. /** max number of documents */
  814. limit?: number;
  815. /** keep temporary data default: false */
  816. keeptemp?: boolean;
  817. /** finalize function */
  818. finalize?: (key: Key, val: Val) => Val;
  819. /** scope variables exposed to map/reduce/finalize during execution */
  820. scope?: any;
  821. /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */
  822. jsMode?: boolean;
  823. /** provide statistics on job execution time. default: false */
  824. verbose?: boolean;
  825. readPreference?: string;
  826. /** sets the output target for the map reduce job. default: {inline: 1} */
  827. out?: {
  828. /** the results are returned in an array */
  829. inline?: number;
  830. /**
  831. * {replace: 'collectionName'} add the results to collectionName: the
  832. * results replace the collection
  833. */
  834. replace?: string;
  835. /**
  836. * {reduce: 'collectionName'} add the results to collectionName: if
  837. * dups are detected, uses the reducer / finalize functions
  838. */
  839. reduce?: string;
  840. /**
  841. * {merge: 'collectionName'} add the results to collectionName: if
  842. * dups exist the new docs overwrite the old
  843. */
  844. merge?: string;
  845. };
  846. }
  847. interface GeoSearchOptions {
  848. /** x,y point to search for */
  849. near: number[];
  850. /** the maximum distance from the point near that a result can be */
  851. maxDistance: number;
  852. /** The maximum number of results to return */
  853. limit?: number;
  854. /** return the raw object instead of the Mongoose Model */
  855. lean?: boolean;
  856. }
  857. interface PopulateOptions {
  858. /** space delimited path(s) to populate */
  859. path: string;
  860. /** fields to select */
  861. select?: any;
  862. /** query conditions to match */
  863. match?: any;
  864. /** optional model to use for population */
  865. model?: string | Model<any>;
  866. /** optional query options like sort, limit, etc */
  867. options?: any;
  868. /** deep populate */
  869. populate?: PopulateOptions | Array<PopulateOptions>;
  870. /**
  871. * If true Mongoose will always set `path` to an array, if false Mongoose will
  872. * always set `path` to a document. Inferred from schema by default.
  873. */
  874. justOne?: boolean;
  875. /** transform function to call on every populated doc */
  876. transform?: (doc: any, id: any) => any;
  877. }
  878. interface ToObjectOptions {
  879. /** apply all getters (path and virtual getters) */
  880. getters?: boolean;
  881. /** apply virtual getters (can override getters option) */
  882. virtuals?: boolean;
  883. /** if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. */
  884. aliases?: boolean;
  885. /** remove empty objects (defaults to true) */
  886. minimize?: boolean;
  887. /** if set, mongoose will call this function to allow you to transform the returned object */
  888. transform?: (doc: any, ret: any, options: any) => any;
  889. /** if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. */
  890. depopulate?: boolean;
  891. /** if false, exclude the version key (`__v` by default) from the output */
  892. versionKey?: boolean;
  893. /** if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. */
  894. flattenMaps?: boolean;
  895. /** 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. */
  896. useProjection?: boolean;
  897. }
  898. type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init';
  899. type MongooseQueryMiddleware = 'count' | 'deleteMany' | 'deleteOne' | 'distinct' | 'find' | 'findOne' | 'findOneAndDelete' | 'findOneAndRemove' | 'findOneAndUpdate' | 'remove' | 'update' | 'updateOne' | 'updateMany';
  900. type SchemaPreOptions = { document?: boolean, query?: boolean };
  901. type SchemaPostOptions = { document?: boolean, query?: boolean };
  902. type ExtractQueryHelpers<M> = M extends Model<any, infer TQueryHelpers> ? TQueryHelpers : {};
  903. type ExtractMethods<M> = M extends Model<any, any, infer TMethods> ? TMethods : {};
  904. type PreMiddlewareFunction<T> = (this: T, next: (err?: CallbackError) => void) => void | Promise<void>;
  905. type PreSaveMiddlewareFunction<T> = (this: T, next: (err?: CallbackError) => void, opts: SaveOptions) => void | Promise<void>;
  906. type PostMiddlewareFunction<ThisType, ResType = any> = (this: ThisType, res: ResType, next: (err?: CallbackError) => void) => void | Promise<void>;
  907. type ErrorHandlingMiddlewareFunction<ThisType, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: (err?: CallbackError) => void) => void;
  908. class Schema<DocType = Document, M extends Model<DocType, any, any> = Model<any, any, any>, SchemaDefinitionType = undefined> extends events.EventEmitter {
  909. /**
  910. * Create a new schema
  911. */
  912. constructor(definition?: SchemaDefinition<DocumentDefinition<SchemaDefinitionType>>, options?: SchemaOptions);
  913. /** Adds key path / schema type pairs to this schema. */
  914. add(obj: SchemaDefinition<DocumentDefinition<SchemaDefinitionType>> | Schema, prefix?: string): this;
  915. /**
  916. * Array of child schemas (from document arrays and single nested subdocs)
  917. * and their corresponding compiled models. Each element of the array is
  918. * an object with 2 properties: `schema` and `model`.
  919. */
  920. childSchemas: { schema: Schema, model: any }[];
  921. /** Returns a copy of this schema */
  922. clone(): Schema;
  923. /** Object containing discriminators defined on this schema */
  924. discriminators?: { [name: string]: Schema };
  925. /** Iterates the schemas paths similar to Array#forEach. */
  926. eachPath(fn: (path: string, type: SchemaType) => void): this;
  927. /** Defines an index (most likely compound) for this schema. */
  928. index(fields: any, options?: any): this;
  929. /**
  930. * Returns a list of indexes that this schema declares, via `schema.index()`
  931. * or by `index: true` in a path's options.
  932. */
  933. indexes(): Array<any>;
  934. /** Gets a schema option. */
  935. get(path: string): any;
  936. /**
  937. * 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),
  938. * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
  939. * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
  940. * [statics](http://mongoosejs.com/docs/guide.html#statics), and
  941. * [methods](http://mongoosejs.com/docs/guide.html#methods).
  942. */
  943. // eslint-disable-next-line @typescript-eslint/ban-types
  944. loadClass(model: Function, onlyVirtuals?: boolean): this;
  945. /** Adds an instance method to documents constructed from Models compiled from this schema. */
  946. // eslint-disable-next-line @typescript-eslint/ban-types
  947. method(name: string, fn: (this: EnforceDocument<DocType, ExtractMethods<M>>, ...args: any[]) => any, opts?: any): this;
  948. method(obj: { [name: string]: (this: EnforceDocument<DocType, ExtractMethods<M>>, ...args: any[]) => any }): this;
  949. /** Object of currently defined methods on this schema. */
  950. methods: { [name: string]: (this: EnforceDocument<DocType, ExtractMethods<M>>, ...args: any[]) => any };
  951. /** The original object passed to the schema constructor */
  952. obj: any;
  953. /** Gets/sets schema paths. */
  954. path(path: string): SchemaType;
  955. path(path: string, constructor: any): this;
  956. /** Lists all paths and their type in the schema. */
  957. paths: {
  958. [key: string]: SchemaType;
  959. }
  960. /** Returns the pathType of `path` for this schema. */
  961. pathType(path: string): string;
  962. /** Registers a plugin for this schema. */
  963. plugin(fn: (schema: Schema<DocType, Model<DocType>, SchemaDefinitionType>, opts?: any) => void, opts?: any): this;
  964. /** Defines a post hook for the model. */
  965. post<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T>): this;
  966. post<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
  967. post<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PostMiddlewareFunction<T>): this;
  968. post<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
  969. post<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction<T, Array<any>>): this;
  970. post<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, Array<any>>): this;
  971. post<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<T>): this;
  972. post<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
  973. post<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
  974. post<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
  975. post<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
  976. post<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
  977. post<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
  978. post<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
  979. post<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
  980. post<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
  981. /** Defines a pre hook for the model. */
  982. pre<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: 'save', fn: PreSaveMiddlewareFunction<T>): this;
  983. pre<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
  984. pre<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
  985. pre<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PreMiddlewareFunction<T>): this;
  986. pre<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
  987. pre<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction<T>): this;
  988. pre<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
  989. pre<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array<any>) => void | Promise<void>): this;
  990. pre<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, options: SchemaPreOptions, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array<any>) => void | Promise<void>): this;
  991. /** Object of currently defined query helpers on this schema. */
  992. query: { [name: string]: <T extends QueryWithHelpers<any, EnforceDocument<DocType, ExtractMethods<M>>, ExtractQueryHelpers<M>> = QueryWithHelpers<any, EnforceDocument<DocType, ExtractMethods<M>>, ExtractQueryHelpers<M>>>(this: T, ...args: any[]) => any };
  993. /** Adds a method call to the queue. */
  994. queue(name: string, args: any[]): this;
  995. /** Removes the given `path` (or [`paths`]). */
  996. remove(paths: string | Array<string>): this;
  997. /** Returns an Array of path strings that are required by this schema. */
  998. requiredPaths(invalidate?: boolean): string[];
  999. /** Sets a schema option. */
  1000. set(path: string, value: any, _tags?: any): this;
  1001. /** Adds static "class" methods to Models compiled from this schema. */
  1002. // eslint-disable-next-line @typescript-eslint/ban-types
  1003. static(name: string, fn: (this: M, ...args: any[]) => any): this;
  1004. // eslint-disable-next-line @typescript-eslint/ban-types
  1005. static(obj: { [name: string]: (this: M, ...args: any[]) => any }): this;
  1006. /** Object of currently defined statics on this schema. */
  1007. statics: { [name: string]: (this: M, ...args: any[]) => any };
  1008. /** Creates a virtual type with the given name. */
  1009. virtual(name: string, options?: any): VirtualType;
  1010. /** Object of currently defined virtuals on this schema */
  1011. virtuals: any;
  1012. /** Returns the virtual type with the given `name`. */
  1013. virtualpath(name: string): VirtualType | null;
  1014. }
  1015. type SchemaDefinitionWithBuiltInClass<T extends number | string | boolean | Function> = T extends number
  1016. ? (typeof Number | 'number' | 'Number' | typeof Schema.Types.Number)
  1017. : T extends string
  1018. ? (typeof String | 'string' | 'String' | typeof Schema.Types.String)
  1019. : T extends boolean
  1020. ? (typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean)
  1021. : (Function | string);
  1022. type SchemaDefinitionProperty<T = undefined> = T extends string | number | Function
  1023. ? (SchemaDefinitionWithBuiltInClass<T> | SchemaTypeOptions<T>) :
  1024. SchemaTypeOptions<T extends undefined ? any : T> |
  1025. typeof SchemaType |
  1026. Schema<any, any> |
  1027. Schema<any, any>[] |
  1028. ReadonlyArray<Schema<any, any>> |
  1029. SchemaTypeOptions<T extends undefined ? any : T>[] |
  1030. ReadonlyArray<SchemaTypeOptions<T extends undefined ? any : T>> |
  1031. Function[] |
  1032. SchemaDefinition<T> |
  1033. SchemaDefinition<T>[] |
  1034. ReadonlyArray<SchemaDefinition<T>>;
  1035. type SchemaDefinition<T = undefined> = T extends undefined
  1036. ? { [path: string]: SchemaDefinitionProperty; }
  1037. : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
  1038. interface SchemaOptions {
  1039. /**
  1040. * By default, Mongoose's init() function creates all the indexes defined in your model's schema by
  1041. * calling Model.createIndexes() after you successfully connect to MongoDB. If you want to disable
  1042. * automatic index builds, you can set autoIndex to false.
  1043. */
  1044. autoIndex?: boolean;
  1045. /**
  1046. * If set to `true`, Mongoose will call Model.createCollection() to create the underlying collection
  1047. * in MongoDB if autoCreate is set to true. Calling createCollection() sets the collection's default
  1048. * collation based on the collation option and establishes the collection as a capped collection if
  1049. * you set the capped schema option.
  1050. */
  1051. autoCreate?: boolean;
  1052. /**
  1053. * By default, mongoose buffers commands when the connection goes down until the driver manages to reconnect.
  1054. * To disable buffering, set bufferCommands to false.
  1055. */
  1056. bufferCommands?: boolean;
  1057. /**
  1058. * If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before
  1059. * throwing an error. If not specified, Mongoose will use 10000 (10 seconds).
  1060. */
  1061. bufferTimeoutMS?: number;
  1062. /**
  1063. * Mongoose supports MongoDBs capped collections. To specify the underlying MongoDB collection be capped, set
  1064. * the capped option to the maximum size of the collection in bytes.
  1065. */
  1066. capped?: boolean | number | { size?: number; max?: number; autoIndexId?: boolean; };
  1067. /** Sets a default collation for every query and aggregation. */
  1068. collation?: mongodb.CollationDocument;
  1069. /**
  1070. * Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName
  1071. * method. This method pluralizes the name. Set this option if you need a different name for your collection.
  1072. */
  1073. collection?: string;
  1074. /**
  1075. * When you define a [discriminator](/docs/discriminators.html), Mongoose adds a path to your
  1076. * schema that stores which discriminator a document is an instance of. By default, Mongoose
  1077. * adds an `__t` path, but you can set `discriminatorKey` to overwrite this default.
  1078. */
  1079. discriminatorKey?: string;
  1080. /** defaults to false. */
  1081. emitIndexErrors?: boolean;
  1082. excludeIndexes?: any;
  1083. /**
  1084. * Mongoose assigns each of your schemas an id virtual getter by default which returns the document's _id field
  1085. * cast to a string, or in the case of ObjectIds, its hexString.
  1086. */
  1087. id?: boolean;
  1088. /**
  1089. * Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema
  1090. * constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior. If you
  1091. * don't want an _id added to your schema at all, you may disable it using this option.
  1092. */
  1093. _id?: boolean;
  1094. /**
  1095. * Mongoose will, by default, "minimize" schemas by removing empty objects. This behavior can be
  1096. * overridden by setting minimize option to false. It will then store empty objects.
  1097. */
  1098. minimize?: boolean;
  1099. /**
  1100. * Optimistic concurrency is a strategy to ensure the document you're updating didn't change between when you
  1101. * loaded it using find() or findOne(), and when you update it using save(). Set to `true` to enable
  1102. * optimistic concurrency.
  1103. */
  1104. optimisticConcurrency?: boolean;
  1105. /**
  1106. * Allows setting query#read options at the schema level, providing us a way to apply default ReadPreferences
  1107. * to all queries derived from a model.
  1108. */
  1109. read?: string;
  1110. /** Allows setting write concern at the schema level. */
  1111. writeConcern?: WriteConcern;
  1112. /** defaults to true. */
  1113. safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean };
  1114. /**
  1115. * The shardKey option is used when we have a sharded MongoDB architecture. Each sharded collection is
  1116. * given a shard key which must be present in all insert/update operations. We just need to set this
  1117. * schema option to the same shard key and we'll be all set.
  1118. */
  1119. shardKey?: Record<string, unknown>;
  1120. /**
  1121. * For backwards compatibility, the strict option does not apply to the filter parameter for queries.
  1122. * Mongoose has a separate strictQuery option to toggle strict mode for the filter parameter to queries.
  1123. */
  1124. strictQuery?: boolean | 'throw';
  1125. /**
  1126. * The strict option, (enabled by default), ensures that values passed to our model constructor that were not
  1127. * specified in our schema do not get saved to the db.
  1128. */
  1129. strict?: boolean | 'throw';
  1130. /** Exactly the same as the toObject option but only applies when the document's toJSON method is called. */
  1131. toJSON?: ToObjectOptions;
  1132. /**
  1133. * Documents have a toObject method which converts the mongoose document into a plain JavaScript object.
  1134. * This method accepts a few options. Instead of applying these options on a per-document basis, we may
  1135. * declare the options at the schema level and have them applied to all of the schema's documents by
  1136. * default.
  1137. */
  1138. toObject?: ToObjectOptions;
  1139. /**
  1140. * By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a
  1141. * type declaration. However, for applications like geoJSON, the 'type' property is important. If you want to
  1142. * control which key mongoose uses to find type declarations, set the 'typeKey' schema option.
  1143. */
  1144. typeKey?: string;
  1145. /**
  1146. * Write operations like update(), updateOne(), updateMany(), and findOneAndUpdate() only check the top-level
  1147. * schema's strict mode setting. Set to `true` to use the child schema's `strict` mode setting.
  1148. */
  1149. useNestedStrict?: boolean;
  1150. /** defaults to false */
  1151. usePushEach?: boolean;
  1152. /**
  1153. * By default, documents are automatically validated before they are saved to the database. This is to
  1154. * prevent saving an invalid document. If you want to handle validation manually, and be able to save
  1155. * objects which don't pass validation, you can set validateBeforeSave to false.
  1156. */
  1157. validateBeforeSave?: boolean;
  1158. /**
  1159. * The versionKey is a property set on each document when first created by Mongoose. This keys value
  1160. * contains the internal revision of the document. The versionKey option is a string that represents
  1161. * the path to use for versioning. The default is '__v'.
  1162. */
  1163. versionKey?: string | boolean;
  1164. /**
  1165. * By default, Mongoose will automatically select() any populated paths for you, unless you explicitly exclude them.
  1166. */
  1167. selectPopulatedPaths?: boolean;
  1168. /**
  1169. * skipVersioning allows excluding paths from versioning (i.e., the internal revision will not be
  1170. * incremented even if these paths are updated). DO NOT do this unless you know what you're doing.
  1171. * For subdocuments, include this on the parent document using the fully qualified path.
  1172. */
  1173. skipVersioning?: any;
  1174. /**
  1175. * Validation errors in a single nested schema are reported
  1176. * both on the child and on the parent schema.
  1177. * Set storeSubdocValidationError to false on the child schema
  1178. * to make Mongoose only report the parent error.
  1179. */
  1180. storeSubdocValidationError?: boolean;
  1181. /**
  1182. * The timestamps option tells mongoose to assign createdAt and updatedAt fields to your schema. The type
  1183. * assigned is Date. By default, the names of the fields are createdAt and updatedAt. Customize the
  1184. * field names by setting timestamps.createdAt and timestamps.updatedAt.
  1185. */
  1186. timestamps?: boolean | SchemaTimestampsConfig;
  1187. /**
  1188. * Determines whether a type set to a POJO becomes
  1189. * a Mixed path or a Subdocument (defaults to true).
  1190. */
  1191. typePojoToMixed?: boolean;
  1192. }
  1193. interface SchemaTimestampsConfig {
  1194. createdAt?: boolean | string;
  1195. updatedAt?: boolean | string;
  1196. currentTime?: () => (Date | number);
  1197. }
  1198. type Unpacked<T> = T extends (infer U)[] ? U : T;
  1199. export class SchemaTypeOptions<T> {
  1200. type?:
  1201. T extends string | number | boolean | Function ? SchemaDefinitionWithBuiltInClass<T> :
  1202. T extends Schema<any, any> ? T :
  1203. T extends object[] ? (Schema<Document<Unpacked<T>>>[] | ReadonlyArray<Schema<Document<Unpacked<T>>>>) :
  1204. T extends string[] ? (SchemaDefinitionWithBuiltInClass<string>[] | ReadonlyArray<SchemaDefinitionWithBuiltInClass<string>>) :
  1205. T extends number[] ? (SchemaDefinitionWithBuiltInClass<number>[] | ReadonlyArray<SchemaDefinitionWithBuiltInClass<number>>) :
  1206. T extends boolean[] ? (SchemaDefinitionWithBuiltInClass<boolean>[] | ReadonlyArray<SchemaDefinitionWithBuiltInClass<boolean>>) :
  1207. T extends Function[] ? (SchemaDefinitionWithBuiltInClass<Function>[] | ReadonlyArray<SchemaDefinitionWithBuiltInClass<Function>>) :
  1208. T | typeof SchemaType | Schema<any, any>;
  1209. /** Defines a virtual with the given name that gets/sets this path. */
  1210. alias?: string;
  1211. /** Function or object describing how to validate this schematype. See [validation docs](https://mongoosejs.com/docs/validation.html). */
  1212. // eslint-disable-next-line @typescript-eslint/ban-types
  1213. validate?: RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
  1214. /** Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message. */
  1215. cast?: string;
  1216. /**
  1217. * If true, attach a required validator to this path, which ensures this path
  1218. * path cannot be set to a nullish value. If a function, Mongoose calls the
  1219. * function and only checks for nullish values if the function returns a truthy value.
  1220. */
  1221. required?: boolean | (() => boolean) | [boolean, string] | [() => boolean, string];
  1222. /**
  1223. * The default value for this path. If a function, Mongoose executes the function
  1224. * and uses the return value as the default.
  1225. */
  1226. default?: T | ((this: any, doc: any) => T);
  1227. /**
  1228. * The model that `populate()` should use if populating this path.
  1229. */
  1230. ref?: string | Model<any> | ((this: any, doc: any) => string | Model<any>);
  1231. /**
  1232. * Whether to include or exclude this path by default when loading documents
  1233. * using `find()`, `findOne()`, etc.
  1234. */
  1235. select?: boolean | number;
  1236. /**
  1237. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
  1238. * build an index on this path when the model is compiled.
  1239. */
  1240. index?: boolean | number | IndexOptions | '2d' | '2dsphere' | 'hashed' | 'text';
  1241. /**
  1242. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose
  1243. * will build a unique index on this path when the
  1244. * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator).
  1245. */
  1246. unique?: boolean | number;
  1247. /**
  1248. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
  1249. * disallow changes to this path once the document is saved to the database for the first time. Read more
  1250. * about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html).
  1251. */
  1252. immutable?: boolean | ((this: any, doc: any) => boolean);
  1253. /**
  1254. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
  1255. * build a sparse index on this path.
  1256. */
  1257. sparse?: boolean | number;
  1258. /**
  1259. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose
  1260. * will build a text index on this path.
  1261. */
  1262. text?: boolean | number | any;
  1263. /**
  1264. * Define a transform function for this individual schema type.
  1265. * Only called when calling `toJSON()` or `toObject()`.
  1266. */
  1267. transform?: (this: any, val: T) => any;
  1268. /** defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
  1269. get?: (value: T, schematype?: this) => any;
  1270. /** defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
  1271. set?: (value: T, schematype?: this) => any;
  1272. /** array of allowed values for this path. Allowed for strings, numbers, and arrays of strings */
  1273. enum?: Array<string | number | null> | ReadonlyArray<string | number | null> | { values: Array<string | number | null> | ReadonlyArray<string | number | null>, message?: string } | { [path: string]: string | number | null };
  1274. /** The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths */
  1275. subtype?: number
  1276. /** The minimum value allowed for this path. Only allowed for numbers and dates. */
  1277. min?: number | Date | [number, string] | [Date, string] | readonly [number, string] | readonly [Date, string];
  1278. /** The maximum value allowed for this path. Only allowed for numbers and dates. */
  1279. max?: number | Date | [number, string] | [Date, string] | readonly [number, string] | readonly [Date, string];
  1280. /** Defines a TTL index on this path. Only allowed for dates. */
  1281. expires?: number | Date;
  1282. /** If `true`, Mongoose will skip gathering indexes on subpaths. Only allowed for subdocuments and subdocument arrays. */
  1283. excludeIndexes?: boolean;
  1284. /** If set, overrides the child schema's `_id` option. Only allowed for subdocuments and subdocument arrays. */
  1285. _id?: boolean;
  1286. /** If set, specifies the type of this map's values. Mongoose will cast this map's values to the given type. */
  1287. // eslint-disable-next-line @typescript-eslint/ban-types
  1288. of?: Function | SchemaTypeOptions<any>;
  1289. /** If true, uses Mongoose's default `_id` settings. Only allowed for ObjectIds */
  1290. auto?: boolean;
  1291. /** Attaches a validator that succeeds if the data string matches the given regular expression, and fails otherwise. */
  1292. match?: RegExp;
  1293. /** If truthy, Mongoose will add a custom setter that lowercases this string using JavaScript's built-in `String#toLowerCase()`. */
  1294. lowercase?: boolean;
  1295. /** If truthy, Mongoose will add a custom setter that removes leading and trailing whitespace using JavaScript's built-in `String#trim()`. */
  1296. trim?: boolean;
  1297. /** If truthy, Mongoose will add a custom setter that uppercases this string using JavaScript's built-in `String#toUpperCase()`. */
  1298. uppercase?: boolean;
  1299. /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at least the given number. */
  1300. minlength?: number | [number, string] | readonly [number, string];
  1301. /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at most the given number. */
  1302. maxlength?: number | [number, string] | readonly [number, string];
  1303. [other: string]: any;
  1304. }
  1305. export type RefType =
  1306. | number
  1307. | string
  1308. | Buffer
  1309. | undefined
  1310. | mongoose.Types.ObjectId
  1311. | mongoose.Types.Buffer
  1312. | typeof mongoose.Schema.Types.Number
  1313. | typeof mongoose.Schema.Types.String
  1314. | typeof mongoose.Schema.Types.Buffer
  1315. | typeof mongoose.Schema.Types.ObjectId;
  1316. /**
  1317. * Reference another Model
  1318. */
  1319. export type PopulatedDoc<
  1320. PopulatedType,
  1321. RawId extends RefType = (PopulatedType extends { _id?: RefType; } ? NonNullable<PopulatedType['_id']> : mongoose.Types.ObjectId) | undefined
  1322. > = PopulatedType | RawId;
  1323. interface IndexOptions {
  1324. background?: boolean,
  1325. expires?: number | string
  1326. sparse?: boolean,
  1327. type?: string,
  1328. unique?: boolean
  1329. }
  1330. interface ValidatorProps {
  1331. path: string;
  1332. value: any;
  1333. }
  1334. interface ValidatorMessageFn {
  1335. (props: ValidatorProps): string;
  1336. }
  1337. interface ValidateFn<T> {
  1338. (value: T): boolean;
  1339. }
  1340. interface LegacyAsyncValidateFn<T> {
  1341. (value: T, done: (result: boolean) => void): void;
  1342. }
  1343. interface AsyncValidateFn<T> {
  1344. (value: any): Promise<boolean>;
  1345. }
  1346. interface ValidateOpts<T> {
  1347. msg?: string;
  1348. message?: string | ValidatorMessageFn;
  1349. type?: string;
  1350. validator: ValidateFn<T> | LegacyAsyncValidateFn<T> | AsyncValidateFn<T>;
  1351. }
  1352. class VirtualType {
  1353. /** Applies getters to `value`. */
  1354. applyGetters(value: any, doc: Document): any;
  1355. /** Applies setters to `value`. */
  1356. applySetters(value: any, doc: Document): any;
  1357. /** Adds a custom getter to this virtual. */
  1358. // eslint-disable-next-line @typescript-eslint/ban-types
  1359. get(fn: Function): this;
  1360. /** Adds a custom setter to this virtual. */
  1361. // eslint-disable-next-line @typescript-eslint/ban-types
  1362. set(fn: Function): this;
  1363. }
  1364. namespace Schema {
  1365. namespace Types {
  1366. class Array extends SchemaType implements AcceptsDiscriminator {
  1367. /** This schema type's name, to defend against minifiers that mangle function names. */
  1368. static schemaName: string;
  1369. static options: { castNonArrays: boolean; };
  1370. discriminator<D extends Document>(name: string | number, schema: Schema<D>, value?: string): Model<D>;
  1371. discriminator<T extends Document, U extends Model<T>>(name: string | number, schema: Schema<T, U>, value?: string): U;
  1372. /**
  1373. * Adds an enum validator if this is an array of strings or numbers. Equivalent to
  1374. * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()`
  1375. */
  1376. enum(vals: string[] | number[]): this;
  1377. }
  1378. class Boolean extends SchemaType {
  1379. /** This schema type's name, to defend against minifiers that mangle function names. */
  1380. static schemaName: string;
  1381. /** Configure which values get casted to `true`. */
  1382. static convertToTrue: Set<any>;
  1383. /** Configure which values get casted to `false`. */
  1384. static convertToFalse: Set<any>;
  1385. }
  1386. class Buffer extends SchemaType {
  1387. /** This schema type's name, to defend against minifiers that mangle function names. */
  1388. static schemaName: string;
  1389. /**
  1390. * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/)
  1391. * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html).
  1392. */
  1393. subtype(subtype: number): this;
  1394. }
  1395. class Date extends SchemaType {
  1396. /** This schema type's name, to defend against minifiers that mangle function names. */
  1397. static schemaName: string;
  1398. /** Declares a TTL index (rounded to the nearest second) for _Date_ types only. */
  1399. expires(when: number | string): this;
  1400. /** Sets a maximum date validator. */
  1401. max(value: Date, message: string): this;
  1402. /** Sets a minimum date validator. */
  1403. min(value: Date, message: string): this;
  1404. }
  1405. class Decimal128 extends SchemaType {
  1406. /** This schema type's name, to defend against minifiers that mangle function names. */
  1407. static schemaName: string;
  1408. }
  1409. class DocumentArray extends SchemaType implements AcceptsDiscriminator {
  1410. /** This schema type's name, to defend against minifiers that mangle function names. */
  1411. static schemaName: string;
  1412. static options: { castNonArrays: boolean; };
  1413. discriminator<D extends Document>(name: string | number, schema: Schema<D>, value?: string): Model<D>;
  1414. discriminator<T extends Document, U extends Model<T>>(name: string | number, schema: Schema<T, U>, value?: string): U;
  1415. /** The schema used for documents in this array */
  1416. schema: Schema;
  1417. }
  1418. class Map extends SchemaType {
  1419. /** This schema type's name, to defend against minifiers that mangle function names. */
  1420. static schemaName: string;
  1421. }
  1422. class Mixed extends SchemaType {
  1423. /** This schema type's name, to defend against minifiers that mangle function names. */
  1424. static schemaName: string;
  1425. }
  1426. class Number extends SchemaType {
  1427. /** This schema type's name, to defend against minifiers that mangle function names. */
  1428. static schemaName: string;
  1429. /** Sets a enum validator */
  1430. enum(vals: number[]): this;
  1431. /** Sets a maximum number validator. */
  1432. max(value: number, message: string): this;
  1433. /** Sets a minimum number validator. */
  1434. min(value: number, message: string): this;
  1435. }
  1436. class ObjectId extends SchemaType {
  1437. /** This schema type's name, to defend against minifiers that mangle function names. */
  1438. static schemaName: string;
  1439. /** Adds an auto-generated ObjectId default if turnOn is true. */
  1440. auto(turnOn: boolean): this;
  1441. }
  1442. class Embedded extends SchemaType {
  1443. /** This schema type's name, to defend against minifiers that mangle function names. */
  1444. static schemaName: string;
  1445. /** The document's schema */
  1446. schema: Schema;
  1447. }
  1448. class String extends SchemaType {
  1449. /** This schema type's name, to defend against minifiers that mangle function names. */
  1450. static schemaName: string;
  1451. /** Adds an enum validator */
  1452. enum(vals: string[] | any): this;
  1453. /** Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
  1454. lowercase(shouldApply?: boolean): this;
  1455. /** Sets a regexp validator. */
  1456. match(value: RegExp, message: string): this;
  1457. /** Sets a maximum length validator. */
  1458. maxlength(value: number, message: string): this;
  1459. /** Sets a minimum length validator. */
  1460. minlength(value: number, message: string): this;
  1461. /** Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
  1462. trim(shouldTrim?: boolean): this;
  1463. /** Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
  1464. uppercase(shouldApply?: boolean): this;
  1465. }
  1466. }
  1467. }
  1468. namespace Types {
  1469. class Array<T> extends global.Array<T> {
  1470. /** Pops the array atomically at most one time per document `save()`. */
  1471. $pop(): T;
  1472. /** Atomically shifts the array at most one time per document `save()`. */
  1473. $shift(): T;
  1474. /** Adds values to the array if not already present. */
  1475. addToSet(...args: any[]): any[];
  1476. isMongooseArray: true;
  1477. /** Pushes items to the array non-atomically. */
  1478. nonAtomicPush(...args: any[]): number;
  1479. /** Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. */
  1480. push(...args: any[]): number;
  1481. /**
  1482. * Pulls items from the array atomically. Equality is determined by casting
  1483. * the provided value to an embedded document and comparing using
  1484. * [the `Document.equals()` function.](./api.html#document_Document-equals)
  1485. */
  1486. pull(...args: any[]): this;
  1487. /**
  1488. * Alias of [pull](#mongoosearray_MongooseArray-pull)
  1489. */
  1490. remove(...args: any[]): this;
  1491. /** Sets the casted `val` at index `i` and marks the array modified. */
  1492. set(i: number, val: T): this;
  1493. /** Atomically shifts the array at most one time per document `save()`. */
  1494. shift(): T;
  1495. /** Returns a native js Array. */
  1496. toObject(options?: ToObjectOptions): any;
  1497. toObject<T>(options?: ToObjectOptions): T;
  1498. /** Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. */
  1499. unshift(...args: any[]): number;
  1500. }
  1501. class Buffer extends global.Buffer {
  1502. /** Sets the subtype option and marks the buffer modified. */
  1503. subtype(subtype: number | ToObjectOptions): void;
  1504. /** Converts this buffer to its Binary type representation. */
  1505. toObject(subtype?: number): mongodb.Binary;
  1506. }
  1507. class Decimal128 extends mongodb.Decimal128 { }
  1508. class DocumentArray<T extends Document> extends Types.Array<T> {
  1509. /** DocumentArray constructor */
  1510. constructor(values: any[]);
  1511. isMongooseDocumentArray: true;
  1512. /** Creates a subdocument casted to this schema. */
  1513. create(obj: any): T;
  1514. /** Searches array items for the first document with a matching _id. */
  1515. id(id: any): T | null;
  1516. }
  1517. class EmbeddedDocument extends Document {
  1518. /** Returns the top level document of this sub-document. */
  1519. ownerDocument(): Document;
  1520. /** Returns this sub-documents parent document. */
  1521. parent(): Document;
  1522. /** Returns this sub-documents parent document. */
  1523. $parent(): Document;
  1524. /** Returns this sub-documents parent array. */
  1525. parentArray(): DocumentArray<Document>;
  1526. }
  1527. class Map<V> extends global.Map<string, V> {
  1528. /** Converts a Mongoose map into a vanilla JavaScript map. */
  1529. toObject(options?: ToObjectOptions & { flattenMaps?: boolean }): any;
  1530. }
  1531. const ObjectId: ObjectIdConstructor;
  1532. class _ObjectId extends mongodb.ObjectID {
  1533. _id?: ObjectId;
  1534. }
  1535. // Expose static methods of `mongodb.ObjectID` and allow calling without `new`
  1536. type ObjectIdConstructor = typeof _ObjectId & {
  1537. (val?: string | number): ObjectId;
  1538. };
  1539. // var objectId: mongoose.Types.ObjectId should reference mongodb.ObjectID not
  1540. // the ObjectIdConstructor, so we add the interface below
  1541. // eslint-disable-next-line @typescript-eslint/no-empty-interface
  1542. interface ObjectId extends mongodb.ObjectID { }
  1543. class Subdocument extends Document {
  1544. $isSingleNested: true;
  1545. /** Returns the top level document of this sub-document. */
  1546. ownerDocument(): Document;
  1547. /** Returns this sub-documents parent document. */
  1548. parent(): Document;
  1549. /** Returns this sub-documents parent document. */
  1550. $parent(): Document;
  1551. }
  1552. }
  1553. type ReturnsNewDoc = { new: true } | { returnOriginal: false } | {returnDocument: 'after'};
  1554. type QueryWithHelpers<ResultType, DocType extends Document, THelpers = {}> = Query<ResultType, DocType, THelpers> & THelpers;
  1555. class Query<ResultType, DocType extends Document, THelpers = {}> {
  1556. _mongooseOptions: MongooseQueryOptions;
  1557. /**
  1558. * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
  1559. * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
  1560. * This is equivalent to calling `.cursor()` with no arguments.
  1561. */
  1562. [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
  1563. /** Executes the query */
  1564. exec(): Promise<ResultType>;
  1565. exec(callback?: (err: CallbackError, res: ResultType) => void): void;
  1566. // @todo: this doesn't seem right
  1567. exec(callback?: (err: any, result: ResultType) => void): Promise<ResultType> | any;
  1568. // eslint-disable-next-line @typescript-eslint/ban-types
  1569. $where(argument: string | Function): QueryWithHelpers<DocType[], DocType, THelpers>;
  1570. /** Specifies an `$all` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1571. all(val: Array<any>): this;
  1572. all(path: string, val: Array<any>): this;
  1573. /** Specifies arguments for an `$and` condition. */
  1574. and(array: FilterQuery<DocType>[]): this;
  1575. /** Specifies the batchSize option. */
  1576. batchSize(val: number): this;
  1577. /** Specifies a `$box` condition */
  1578. box(val: any): this;
  1579. box(lower: number[], upper: number[]): this;
  1580. cast(model: Model<any, THelpers> | null, obj: any): UpdateQuery<DocType>;
  1581. /**
  1582. * Executes the query returning a `Promise` which will be
  1583. * resolved with either the doc(s) or rejected with the error.
  1584. * Like `.then()`, but only takes a rejection handler.
  1585. */
  1586. catch: Promise<ResultType>['catch'];
  1587. /** Specifies a `$center` or `$centerSphere` condition. */
  1588. circle(area: any): this;
  1589. circle(path: string, area: any): this;
  1590. /** Adds a collation to this op (MongoDB 3.4 and up) */
  1591. collation(value: mongodb.CollationDocument): this;
  1592. /** Specifies the `comment` option. */
  1593. comment(val: string): this;
  1594. /** Specifies this query as a `count` query. */
  1595. count(callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1596. count(criteria: FilterQuery<DocType>, callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1597. /** Specifies this query as a `countDocuments` query. */
  1598. countDocuments(callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1599. countDocuments(criteria: FilterQuery<DocType>, callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1600. /**
  1601. * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
  1602. * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
  1603. */
  1604. cursor(options?: any): QueryCursor<DocType>;
  1605. /**
  1606. * Declare and/or execute this query as a `deleteMany()` operation. Works like
  1607. * remove, except it deletes _every_ document that matches `filter` in the
  1608. * collection, regardless of the value of `single`.
  1609. */
  1610. deleteMany(filter?: FilterQuery<DocType>, options?: QueryOptions, callback?: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1611. deleteMany(filter: FilterQuery<DocType>, callback: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1612. deleteMany(callback: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1613. /**
  1614. * Declare and/or execute this query as a `deleteOne()` operation. Works like
  1615. * remove, except it deletes at most one document regardless of the `single`
  1616. * option.
  1617. */
  1618. deleteOne(filter?: FilterQuery<DocType>, options?: QueryOptions, callback?: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1619. deleteOne(filter: FilterQuery<DocType>, callback: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1620. deleteOne(callback: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1621. /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
  1622. distinct(field: string, filter?: FilterQuery<DocType>, callback?: (err: any, count: number) => void): QueryWithHelpers<Array<any>, DocType, THelpers>;
  1623. /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1624. // eslint-disable-next-line @typescript-eslint/ban-types
  1625. elemMatch(val: Function | any): this;
  1626. // eslint-disable-next-line @typescript-eslint/ban-types
  1627. elemMatch(path: string, val: Function | any): this;
  1628. /**
  1629. * Gets/sets the error flag on this query. If this flag is not null or
  1630. * undefined, the `exec()` promise will reject without executing.
  1631. */
  1632. error(): NativeError | null;
  1633. error(val: NativeError | null): this;
  1634. /** Specifies the complementary comparison value for paths specified with `where()` */
  1635. equals(val: any): this;
  1636. /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
  1637. estimatedDocumentCount(options?: QueryOptions, callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1638. /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1639. exists(val: boolean): this;
  1640. exists(path: string, val: boolean): this;
  1641. /**
  1642. * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
  1643. * which makes this query return detailed execution stats instead of the actual
  1644. * query result. This method is useful for determining what index your queries
  1645. * use.
  1646. */
  1647. explain(verbose?: string): this;
  1648. /** Creates a `find` query: gets a list of documents that match `filter`. */
  1649. find(callback?: (err: any, docs: DocType[]) => void): QueryWithHelpers<Array<DocType>, DocType, THelpers>;
  1650. find(filter: FilterQuery<DocType>, callback?: (err: any, docs: DocType[]) => void): QueryWithHelpers<Array<DocType>, DocType, THelpers>;
  1651. find(filter: FilterQuery<DocType>, projection?: any | null, options?: QueryOptions | null, callback?: (err: CallbackError, docs: DocType[]) => void): QueryWithHelpers<Array<DocType>, DocType, THelpers>;
  1652. /** Declares the query a findOne operation. When executed, the first found document is passed to the callback. */
  1653. findOne(filter?: FilterQuery<DocType>, projection?: any | null, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1654. /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
  1655. findOneAndDelete(filter?: FilterQuery<DocType>, options?: QueryOptions | null, callback?: (err: any, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1656. /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
  1657. findOneAndRemove(filter?: FilterQuery<DocType>, options?: QueryOptions | null, callback?: (err: any, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1658. /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
  1659. findOneAndUpdate(filter: FilterQuery<DocType>, update: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options: QueryOptions & { rawResult: true }, callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<DocType>, res: any) => void): QueryWithHelpers<mongodb.FindAndModifyWriteOpResultObject<DocType>, DocType, THelpers>;
  1660. findOneAndUpdate(filter: FilterQuery<DocType>, update: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: any, doc: DocType, res: any) => void): QueryWithHelpers<DocType, DocType, THelpers>;
  1661. findOneAndUpdate(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: any, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1662. /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
  1663. findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: any, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1664. /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
  1665. findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options: QueryOptions & { rawResult: true }, callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<DocType>, res: any) => void): QueryWithHelpers<mongodb.FindAndModifyWriteOpResultObject<DocType>, DocType, THelpers>;
  1666. findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: any, doc: DocType, res: any) => void): QueryWithHelpers<DocType, DocType, THelpers>;
  1667. findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: any, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1668. /** Specifies a `$geometry` condition */
  1669. geometry(object: { type: string, coordinates: any[] }): this;
  1670. /**
  1671. * For update operations, returns the value of a path in the update's `$set`.
  1672. * Useful for writing getters/setters that can work with both update operations
  1673. * and `save()`.
  1674. */
  1675. get(path: string): any;
  1676. /** Returns the current query filter (also known as conditions) as a POJO. */
  1677. getFilter(): FilterQuery<DocType>;
  1678. /** Gets query options. */
  1679. getOptions(): QueryOptions;
  1680. /** Gets a list of paths to be populated by this query */
  1681. getPopulatedPaths(): Array<string>;
  1682. /** Returns the current query filter. Equivalent to `getFilter()`. */
  1683. getQuery(): FilterQuery<DocType>;
  1684. /** Returns the current update operations as a JSON object. */
  1685. getUpdate(): UpdateQuery<DocType> | UpdateWithAggregationPipeline | null;
  1686. /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1687. gt(val: number): this;
  1688. gt(path: string, val: number): this;
  1689. /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1690. gte(val: number): this;
  1691. gte(path: string, val: number): this;
  1692. /** Sets query hints. */
  1693. hint(val: any): this;
  1694. /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1695. in(val: Array<any>): this;
  1696. in(path: string, val: Array<any>): this;
  1697. /** Declares an intersects query for `geometry()`. */
  1698. intersects(arg?: any): this;
  1699. /** Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. */
  1700. j(val: boolean | null): this;
  1701. /** Sets the lean option. */
  1702. lean<LeanResultType = LeanDocumentOrArray<ResultType>>(val?: boolean | any): QueryWithHelpers<LeanResultType, DocType, THelpers>;
  1703. /** Specifies the maximum number of documents the query will return. */
  1704. limit(val: number): this;
  1705. /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1706. lt(val: number): this;
  1707. lt(path: string, val: number): this;
  1708. /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1709. lte(val: number): this;
  1710. lte(path: string, val: number): this;
  1711. /**
  1712. * Runs a function `fn` and treats the return value of `fn` as the new value
  1713. * for the query to resolve to.
  1714. */
  1715. map<MappedType>(fn: (doc: DocType) => MappedType): QueryWithHelpers<ResultType extends unknown[] ? MappedType[] : MappedType, DocType, THelpers>;
  1716. /** Specifies an `$maxDistance` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1717. maxDistance(val: number): this;
  1718. maxDistance(path: string, val: number): this;
  1719. /** Specifies the maxScan option. */
  1720. maxScan(val: number): this;
  1721. /**
  1722. * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/)
  1723. * option. This will tell the MongoDB server to abort if the query or write op
  1724. * has been running for more than `ms` milliseconds.
  1725. */
  1726. maxTimeMS(ms: number): this;
  1727. /** Merges another Query or conditions object into this one. */
  1728. merge(source: Query<any, any> | FilterQuery<DocType>): this;
  1729. /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
  1730. mod(val: Array<number>): this;
  1731. mod(path: string, val: Array<number>): this;
  1732. /**
  1733. * Getter/setter around the current mongoose-specific options for this query
  1734. * Below are the current Mongoose-specific options.
  1735. */
  1736. mongooseOptions(val?: MongooseQueryOptions): MongooseQueryOptions;
  1737. /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1738. ne(val: any): this;
  1739. ne(path: string, val: any): this;
  1740. /** Specifies a `$near` or `$nearSphere` condition */
  1741. near(val: any): this;
  1742. near(path: string, val: any): this;
  1743. /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1744. nin(val: Array<any>): this;
  1745. nin(path: string, val: Array<any>): this;
  1746. /** Specifies arguments for an `$nor` condition. */
  1747. nor(array: Array<FilterQuery<DocType>>): this;
  1748. /** Specifies arguments for an `$or` condition. */
  1749. or(array: Array<FilterQuery<DocType>>): this;
  1750. /**
  1751. * Make this query throw an error if no documents match the given `filter`.
  1752. * This is handy for integrating with async/await, because `orFail()` saves you
  1753. * an extra `if` statement to check if no document was found.
  1754. */
  1755. orFail(err?: NativeError | (() => NativeError)): QueryWithHelpers<NonNullable<ResultType>, DocType, THelpers>;
  1756. /** Specifies a `$polygon` condition */
  1757. polygon(...coordinatePairs: number[][]): this;
  1758. polygon(path: string, ...coordinatePairs: number[][]): this;
  1759. /** Specifies paths which should be populated with other documents. */
  1760. populate(path: string | any, select?: string | any, model?: string | Model<any, THelpers>, match?: any): this;
  1761. populate(options: PopulateOptions | Array<PopulateOptions>): this;
  1762. /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */
  1763. projection(fields?: any | null): any;
  1764. /** Determines the MongoDB nodes from which to read. */
  1765. read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
  1766. /** Sets the readConcern option for the query. */
  1767. readConcern(level: string): this;
  1768. /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1769. regex(val: string | RegExp): this;
  1770. regex(path: string, val: string | RegExp): this;
  1771. /**
  1772. * Declare and/or execute this query as a remove() operation. `remove()` is
  1773. * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne)
  1774. * or [`deleteMany()`](#query_Query-deleteMany) instead.
  1775. */
  1776. remove(filter?: FilterQuery<DocType>, callback?: (err: CallbackError, res: mongodb.WriteOpResult['result']) => void): QueryWithHelpers<mongodb.WriteOpResult['result'], DocType, THelpers>;
  1777. /**
  1778. * Declare and/or execute this query as a replaceOne() operation. Same as
  1779. * `update()`, except MongoDB will replace the existing document and will
  1780. * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
  1781. */
  1782. replaceOne(filter?: FilterQuery<DocType>, replacement?: DocumentDefinition<DocType>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1783. /** Specifies which document fields to include or exclude (also known as the query "projection") */
  1784. select(arg: string | any): this;
  1785. /** Determines if field selection has been made. */
  1786. selected(): boolean;
  1787. /** Determines if exclusive field selection has been made. */
  1788. selectedExclusively(): boolean;
  1789. /** Determines if inclusive field selection has been made. */
  1790. selectedInclusively(): boolean;
  1791. /**
  1792. * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/)
  1793. * associated with this query. Sessions are how you mark a query as part of a
  1794. * [transaction](/docs/transactions.html).
  1795. */
  1796. session(session: mongodb.ClientSession | null): this;
  1797. /**
  1798. * Adds a `$set` to this query's update without changing the operation.
  1799. * This is useful for query middleware so you can add an update regardless
  1800. * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc.
  1801. */
  1802. set(path: string, value: any): this;
  1803. /** Sets query options. Some options only make sense for certain operations. */
  1804. setOptions(options: QueryOptions, overwrite?: boolean): this;
  1805. /** Sets the query conditions to the provided JSON object. */
  1806. setQuery(val: FilterQuery<DocType> | null): void;
  1807. setUpdate(update: UpdateQuery<DocType> | UpdateWithAggregationPipeline): void;
  1808. /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1809. size(val: number): this;
  1810. size(path: string, val: number): this;
  1811. /** Specifies the number of documents to skip. */
  1812. skip(val: number): this;
  1813. /** Specifies a `$slice` projection for an array. */
  1814. slice(val: number | Array<number>): this;
  1815. slice(path: string, val: number | Array<number>): this;
  1816. /** Specifies this query as a `snapshot` query. */
  1817. snapshot(val?: boolean): this;
  1818. /** Sets the sort order. If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. */
  1819. sort(arg: string | any): this;
  1820. /** Sets the tailable option (for use with capped collections). */
  1821. tailable(bool?: boolean, opts?: {
  1822. numberOfRetries?: number;
  1823. tailableRetryInterval?: number;
  1824. }): this;
  1825. /**
  1826. * Executes the query returning a `Promise` which will be
  1827. * resolved with either the doc(s) or rejected with the error.
  1828. */
  1829. then: Promise<ResultType>['then'];
  1830. /** Converts this query to a customized, reusable query constructor with all arguments and options retained. */
  1831. toConstructor(): new (...args: any[]) => QueryWithHelpers<ResultType, DocType, THelpers>;
  1832. /** Declare and/or execute this query as an update() operation. */
  1833. update(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: CallbackError, res: UpdateWriteOpResult) => void): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers>;
  1834. /**
  1835. * Declare and/or execute this query as an updateMany() operation. Same as
  1836. * `update()`, except MongoDB will update _all_ documents that match
  1837. * `filter` (as opposed to just the first one) regardless of the value of
  1838. * the `multi` option.
  1839. */
  1840. updateMany(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: CallbackError, res: UpdateWriteOpResult) => void): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers>;
  1841. /**
  1842. * Declare and/or execute this query as an updateOne() operation. Same as
  1843. * `update()`, except it does not support the `multi` or `overwrite` options.
  1844. */
  1845. updateOne(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: CallbackError, res: UpdateWriteOpResult) => void): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers>;
  1846. /**
  1847. * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
  1848. * that must acknowledge this write before this write is considered successful.
  1849. */
  1850. w(val: string | number | null): this;
  1851. /** Specifies a path for use with chaining. */
  1852. where(path: string, val?: any): this;
  1853. where(obj: object): this;
  1854. where(): this;
  1855. /** Defines a `$within` or `$geoWithin` argument for geo-spatial queries. */
  1856. within(val?: any): this;
  1857. /**
  1858. * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to
  1859. * wait for this write to propagate through the replica set before this
  1860. * operation fails. The default is `0`, which means no timeout.
  1861. */
  1862. wtimeout(ms: number): this;
  1863. }
  1864. type _FilterQuery<T> = {
  1865. [P in keyof T]?: P extends '_id'
  1866. ? [Extract<T[P], mongodb.ObjectId>] extends [never]
  1867. ? mongodb.Condition<T[P]>
  1868. : mongodb.Condition<T[P] | string | { _id: mongodb.ObjectId }>
  1869. : [Extract<T[P], mongodb.ObjectId>] extends [never]
  1870. ? mongodb.Condition<T[P]>
  1871. : mongodb.Condition<T[P] | string>;
  1872. } &
  1873. mongodb.RootQuerySelector<T>;
  1874. export type FilterQuery<T> = _FilterQuery<DocumentDefinition<T>>;
  1875. type NumericTypes = number | mongodb.Decimal128 | mongodb.Double | mongodb.Int32 | mongodb.Long;
  1876. type KeysOfAType<TSchema, Type> = {
  1877. [key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? key : never;
  1878. }[keyof TSchema];
  1879. type PullOperator<TSchema> = {
  1880. [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?:
  1881. | Partial<Unpacked<TSchema[key]>>
  1882. | mongodb.ObjectQuerySelector<Unpacked<TSchema[key]>>
  1883. // Doesn't look like TypeScript has good support for creating an
  1884. // object containing dotted keys:
  1885. // https://stackoverflow.com/questions/58434389/typescript-deep-keyof-of-a-nested-object
  1886. | mongodb.QuerySelector<any>
  1887. | any;
  1888. } | any; // Because TS doesn't have good support for creating an object with dotted keys, including `.$.` re: #10075
  1889. /** @see https://docs.mongodb.com/manual/reference/operator/update */
  1890. type _UpdateQuery<TSchema> = {
  1891. /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
  1892. $currentDate?: mongodb.OnlyFieldsOfType<TSchema, NativeDate | mongodb.Timestamp, true | { $type: 'date' | 'timestamp' }> | any;
  1893. $inc?: mongodb.OnlyFieldsOfType<TSchema, NumericTypes | undefined> | any;
  1894. $min?: mongodb.MatchKeysAndValues<TSchema>;
  1895. $max?: mongodb.MatchKeysAndValues<TSchema>;
  1896. $mul?: mongodb.OnlyFieldsOfType<TSchema, NumericTypes | undefined> | any;
  1897. $rename?: { [key: string]: string };
  1898. $set?: mongodb.MatchKeysAndValues<TSchema>;
  1899. $setOnInsert?: mongodb.MatchKeysAndValues<TSchema>;
  1900. $unset?: mongodb.OnlyFieldsOfType<TSchema, any, any> | any;
  1901. /** @see https://docs.mongodb.com/manual/reference/operator/update-array/ */
  1902. $addToSet?: mongodb.SetFields<TSchema> | any;
  1903. $pop?: mongodb.OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1> | any;
  1904. $pull?: PullOperator<TSchema>;
  1905. $push?: mongodb.PushOperator<TSchema> | any;
  1906. $pullAll?: mongodb.PullAllOperator<TSchema> | any;
  1907. /** @see https://docs.mongodb.com/manual/reference/operator/update-bitwise/ */
  1908. $bit?: {
  1909. [key: string]: { [key in 'and' | 'or' | 'xor']?: number };
  1910. };
  1911. };
  1912. type UpdateWithAggregationPipeline = UpdateAggregationStage[];
  1913. type UpdateAggregationStage = { $addFields: any } |
  1914. { $set: any } |
  1915. { $project: any } |
  1916. { $unset: any } |
  1917. { $replaceRoot: any } |
  1918. { $replaceWith: any };
  1919. export type UpdateQuery<T> = (_UpdateQuery<DocumentDefinition<T>> & mongodb.MatchKeysAndValues<DocumentDefinition<T>>);
  1920. type _AllowStringsForIds<T> = {
  1921. [K in keyof T]: [Extract<T[K], mongodb.ObjectId>] extends [never] ? T[K] : T[K] | string;
  1922. };
  1923. export type DocumentDefinition<T> = _AllowStringsForIds<LeanDocument<T>>;
  1924. type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
  1925. type TreatAsPrimitives = actualPrimitives |
  1926. // eslint-disable-next-line no-undef
  1927. Date | RegExp | symbol | Error | BigInt | Types.ObjectId;
  1928. type LeanType<T> =
  1929. 0 extends (1 & T) ? T : // any
  1930. T extends TreatAsPrimitives ? T : // primitives
  1931. LeanDocument<T>; // Documents and everything else
  1932. type LeanArray<T extends unknown[]> = T extends unknown[][] ? LeanArray<T[number]>[] : LeanType<T[number]>[];
  1933. export type _LeanDocument<T> = {
  1934. [K in keyof T]:
  1935. 0 extends (1 & T[K]) ? T[K] : // any
  1936. T[K] extends unknown[] ? LeanArray<T[K]> : // Array
  1937. T[K] extends Document ? LeanDocument<T[K]> : // Subdocument
  1938. T[K];
  1939. };
  1940. export type LeanDocument<T> = Omit<_LeanDocument<T>, Exclude<keyof Document, '_id' | 'id' | '__v'> | '$isSingleNested'>;
  1941. export type LeanDocumentOrArray<T> = 0 extends (1 & T) ? T :
  1942. T extends unknown[] ? LeanDocument<T[number]>[] :
  1943. T extends Document ? LeanDocument<T> :
  1944. T;
  1945. class QueryCursor<DocType extends Document> extends stream.Readable {
  1946. [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
  1947. /**
  1948. * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
  1949. * Useful for setting the `noCursorTimeout` and `tailable` flags.
  1950. */
  1951. addCursorFlag(flag: string, value: boolean): this;
  1952. /**
  1953. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  1954. * `next()` will error.
  1955. */
  1956. close(): Promise<void>;
  1957. close(callback: (err: CallbackError) => void): void;
  1958. /**
  1959. * Execute `fn` for every document(s) in the cursor. If batchSize is provided
  1960. * `fn` will be executed for each batch of documents. If `fn` returns a promise,
  1961. * will wait for the promise to resolve before iterating on to the next one.
  1962. * Returns a promise that resolves when done.
  1963. */
  1964. eachAsync(fn: (doc: DocType) => any, options?: { parallel?: number }): Promise<void>;
  1965. eachAsync(fn: (doc: DocType[]) => any, options: { parallel?: number, batchSize: number }): Promise<void>;
  1966. eachAsync(fn: (doc: DocType) => any, options?: { parallel?: number, batchSize?: number }, cb?: (err: CallbackError) => void): void;
  1967. eachAsync(fn: (doc: DocType[]) => any, options: { parallel?: number, batchSize: number }, cb?: (err: CallbackError) => void): void;
  1968. /**
  1969. * Registers a transform function which subsequently maps documents retrieved
  1970. * via the streams interface or `.next()`
  1971. */
  1972. map<ResultType extends Document>(fn: (res: DocType) => ResultType): QueryCursor<ResultType>;
  1973. /**
  1974. * Get the next document from this cursor. Will return `null` when there are
  1975. * no documents left.
  1976. */
  1977. next(): Promise<DocType>;
  1978. next(callback: (err: CallbackError, doc: DocType | null) => void): void;
  1979. options: any;
  1980. }
  1981. class Aggregate<R> {
  1982. /**
  1983. * Sets an option on this aggregation. This function will be deprecated in a
  1984. * future release. */
  1985. addCursorFlag(flag: string, value: boolean): this;
  1986. /**
  1987. * Appends a new $addFields operator to this aggregate pipeline.
  1988. * Requires MongoDB v3.4+ to work
  1989. */
  1990. addFields(arg: any): this;
  1991. /** Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) */
  1992. allowDiskUse(value: boolean): this;
  1993. /** Appends new operators to this aggregate pipeline */
  1994. append(...args: any[]): this;
  1995. /**
  1996. * Executes the query returning a `Promise` which will be
  1997. * resolved with either the doc(s) or rejected with the error.
  1998. * Like [`.then()`](#query_Query-then), but only takes a rejection handler.
  1999. */
  2000. catch: Promise<R>['catch'];
  2001. /** Adds a collation. */
  2002. collation(options: mongodb.CollationDocument): this;
  2003. /** Appends a new $count operator to this aggregate pipeline. */
  2004. count(countName: string): this;
  2005. /**
  2006. * Sets the cursor option for the aggregation query (ignored for < 2.6.0).
  2007. */
  2008. cursor(options?: Record<string, unknown>): this;
  2009. /** Executes the aggregate pipeline on the currently bound Model. If cursor option is set, returns a cursor */
  2010. exec(callback?: (err: any, result: R) => void): Promise<R> | any;
  2011. /** Execute the aggregation with explain */
  2012. explain(callback?: (err: CallbackError, result: any) => void): Promise<any>;
  2013. /** Combines multiple aggregation pipelines. */
  2014. facet(options: any): this;
  2015. /** Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. */
  2016. graphLookup(options: any): this;
  2017. /** Appends new custom $group operator to this aggregate pipeline. */
  2018. group(arg: any): this;
  2019. /** Sets the hint option for the aggregation query (ignored for < 3.6.0) */
  2020. hint(value: Record<string, unknown> | string): this;
  2021. /**
  2022. * Appends a new $limit operator to this aggregate pipeline.
  2023. * @param num maximum number of records to pass to the next stage
  2024. */
  2025. limit(num: number): this;
  2026. /** Appends new custom $lookup operator to this aggregate pipeline. */
  2027. lookup(options: any): this;
  2028. /**
  2029. * Appends a new custom $match operator to this aggregate pipeline.
  2030. * @param arg $match operator contents
  2031. */
  2032. match(arg: any): this;
  2033. /**
  2034. * Binds this aggregate to a model.
  2035. * @param model the model to which the aggregate is to be bound
  2036. */
  2037. model(model: any): this;
  2038. /** Returns the current pipeline */
  2039. pipeline(): any[];
  2040. /** Appends a new $project operator to this aggregate pipeline. */
  2041. project(arg: string | Object): this;
  2042. /** Sets the readPreference option for the aggregation query. */
  2043. read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
  2044. /** Sets the readConcern level for the aggregation query. */
  2045. readConcern(level: string): this;
  2046. /** Appends a new $redact operator to this aggregate pipeline. */
  2047. redact(expression: any, thenExpr: string | any, elseExpr: string | any): this;
  2048. /** Appends a new $replaceRoot operator to this aggregate pipeline. */
  2049. replaceRoot(newRoot: object | string): this;
  2050. /**
  2051. * Helper for [Atlas Text Search](https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/)'s
  2052. * `$search` stage.
  2053. */
  2054. search(options: any): this;
  2055. /** Lets you set arbitrary options, for middleware or plugins. */
  2056. option(value: Record<string, unknown>): this;
  2057. /** Appends new custom $sample operator to this aggregate pipeline. */
  2058. sample(size: number): this;
  2059. /** Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html). */
  2060. session(session: mongodb.ClientSession | null): this;
  2061. /**
  2062. * Appends a new $skip operator to this aggregate pipeline.
  2063. * @param num number of records to skip before next stage
  2064. */
  2065. skip(num: number): this;
  2066. /** Appends a new $sort operator to this aggregate pipeline. */
  2067. sort(arg: any): this;
  2068. /** Provides promise for aggregate. */
  2069. then: Promise<R>['then'];
  2070. /**
  2071. * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name
  2072. * or a pipeline object.
  2073. */
  2074. sortByCount(arg: string | any): this;
  2075. /** Appends new custom $unwind operator(s) to this aggregate pipeline. */
  2076. unwind(...args: any[]): this;
  2077. }
  2078. class AggregationCursor extends stream.Readable {
  2079. /**
  2080. * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
  2081. * Useful for setting the `noCursorTimeout` and `tailable` flags.
  2082. */
  2083. addCursorFlag(flag: string, value: boolean): this;
  2084. /**
  2085. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  2086. * `next()` will error.
  2087. */
  2088. close(): Promise<void>;
  2089. close(callback: (err: CallbackError) => void): void;
  2090. /**
  2091. * Execute `fn` for every document(s) in the cursor. If batchSize is provided
  2092. * `fn` will be executed for each batch of documents. If `fn` returns a promise,
  2093. * will wait for the promise to resolve before iterating on to the next one.
  2094. * Returns a promise that resolves when done.
  2095. */
  2096. eachAsync(fn: (doc: any) => any, options?: { parallel?: number, batchSize?: number }): Promise<void>;
  2097. eachAsync(fn: (doc: any) => any, options?: { parallel?: number, batchSize?: number }, cb?: (err: CallbackError) => void): void;
  2098. /**
  2099. * Registers a transform function which subsequently maps documents retrieved
  2100. * via the streams interface or `.next()`
  2101. */
  2102. map(fn: (res: any) => any): this;
  2103. /**
  2104. * Get the next document from this cursor. Will return `null` when there are
  2105. * no documents left.
  2106. */
  2107. next(): Promise<any>;
  2108. next(callback: (err: CallbackError, doc: any) => void): void;
  2109. }
  2110. class SchemaType {
  2111. /** SchemaType constructor */
  2112. constructor(path: string, options?: any, instance?: string);
  2113. /** Get/set the function used to cast arbitrary values to this type. */
  2114. // eslint-disable-next-line @typescript-eslint/ban-types
  2115. static cast(caster?: Function | boolean): Function;
  2116. static checkRequired(checkRequired?: (v: any) => boolean): (v: any) => boolean;
  2117. /** Sets a default option for this schema type. */
  2118. static set(option: string, value: any): void;
  2119. /** Attaches a getter for all instances of this schema type. */
  2120. static get(getter: (value: any) => any): void;
  2121. /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */
  2122. OptionsConstructor: typeof SchemaTypeOptions;
  2123. /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
  2124. cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
  2125. /** Sets a default value for this SchemaType. */
  2126. default(val: any): any;
  2127. /** Adds a getter to this schematype. */
  2128. // eslint-disable-next-line @typescript-eslint/ban-types
  2129. get(fn: Function): this;
  2130. /**
  2131. * Defines this path as immutable. Mongoose prevents you from changing
  2132. * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew).
  2133. */
  2134. immutable(bool: boolean): this;
  2135. /** Declares the index options for this schematype. */
  2136. index(options: any): this;
  2137. /**
  2138. * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
  2139. * looks at to determine the foreign collection it should query.
  2140. */
  2141. ref(ref: string | boolean | Model<any>): this;
  2142. /**
  2143. * Adds a required validator to this SchemaType. The validator gets added
  2144. * to the front of this SchemaType's validators array using unshift().
  2145. */
  2146. required(required: boolean, message?: string): this;
  2147. /** Sets default select() behavior for this path. */
  2148. select(val: boolean): this;
  2149. /** Adds a setter to this schematype. */
  2150. // eslint-disable-next-line @typescript-eslint/ban-types
  2151. set(fn: Function): this;
  2152. /** Declares a sparse index. */
  2153. sparse(bool: boolean): this;
  2154. /** Declares a full text index. */
  2155. text(bool: boolean): this;
  2156. /** Defines a custom function for transforming this path when converting a document to JSON. */
  2157. transform(fn: (value: any) => any): this;
  2158. /** Declares an unique index. */
  2159. unique(bool: boolean): this;
  2160. /** Adds validator(s) for this document path. */
  2161. // eslint-disable-next-line @typescript-eslint/ban-types
  2162. validate(obj: RegExp | Function | any, errorMsg?: string,
  2163. type?: string): this;
  2164. }
  2165. class NativeError extends global.Error { }
  2166. type CallbackError = NativeError | null;
  2167. class Error extends global.Error {
  2168. constructor(msg: string);
  2169. /** The type of error. "MongooseError" for generic errors. */
  2170. name: string;
  2171. static messages: any;
  2172. static Messages: any;
  2173. }
  2174. namespace Error {
  2175. export class CastError extends Error {
  2176. name: 'CastError';
  2177. stringValue: string;
  2178. kind: string;
  2179. value: any;
  2180. path: string;
  2181. reason?: NativeError | null;
  2182. model?: any;
  2183. constructor(type: string, value: any, path: string, reason?: NativeError, schemaType?: SchemaType);
  2184. }
  2185. export class DisconnectedError extends Error {
  2186. name: 'DisconnectedError';
  2187. }
  2188. export class DivergentArrayError extends Error {
  2189. name: 'DivergentArrayError';
  2190. }
  2191. export class MissingSchemaError extends Error {
  2192. name: 'MissingSchemaError';
  2193. }
  2194. export class DocumentNotFoundError extends Error {
  2195. name: 'DocumentNotFoundError';
  2196. result: any;
  2197. numAffected: number;
  2198. filter: any;
  2199. query: any;
  2200. }
  2201. export class ObjectExpectedError extends Error {
  2202. name: 'ObjectExpectedError';
  2203. path: string;
  2204. }
  2205. export class ObjectParameterError extends Error {
  2206. name: 'ObjectParameterError';
  2207. }
  2208. export class OverwriteModelError extends Error {
  2209. name: 'OverwriteModelError';
  2210. }
  2211. export class ParallelSaveError extends Error {
  2212. name: 'ParallelSaveError';
  2213. }
  2214. export class ParallelValidateError extends Error {
  2215. name: 'ParallelValidateError';
  2216. }
  2217. export class MongooseServerSelectionError extends Error {
  2218. name: 'MongooseServerSelectionError';
  2219. }
  2220. export class StrictModeError extends Error {
  2221. name: 'StrictModeError';
  2222. isImmutableError: boolean;
  2223. path: string;
  2224. }
  2225. export class ValidationError extends Error {
  2226. name: 'ValidationError';
  2227. errors: { [path: string]: ValidatorError | CastError };
  2228. }
  2229. export class ValidatorError extends Error {
  2230. name: 'ValidatorError';
  2231. properties: {
  2232. message: string,
  2233. type?: string,
  2234. path?: string,
  2235. value?: any,
  2236. reason?: any
  2237. };
  2238. kind: string;
  2239. path: string;
  2240. value: any;
  2241. reason?: Error | null;
  2242. }
  2243. export class VersionError extends Error {
  2244. name: 'VersionError';
  2245. version: number;
  2246. modifiedPaths: Array<string>;
  2247. }
  2248. }
  2249. /** Deprecated types for backwards compatibility. */
  2250. /** Alias for QueryOptions for backwards compatability. */
  2251. type ModelUpdateOptions = QueryOptions;
  2252. type DocumentQuery<ResultType, DocType extends Document, THelpers = {}> = Query<ResultType, DocType, THelpers>;
  2253. /** Backwards support for DefinitelyTyped */
  2254. interface HookSyncCallback<T> {
  2255. (this: T, next: HookNextFunction, docs: any[]): Promise<any> | void;
  2256. }
  2257. interface HookAsyncCallback<T> {
  2258. (this: T, next: HookNextFunction, done: HookDoneFunction, docs: any[]): Promise<any> | void;
  2259. }
  2260. interface HookErrorCallback {
  2261. (error?: Error): any;
  2262. }
  2263. interface HookNextFunction {
  2264. (error?: Error): any;
  2265. }
  2266. interface HookDoneFunction {
  2267. (error?: Error): any;
  2268. }
  2269. export type SchemaTypeOpts<T> = SchemaTypeOptions<T>;
  2270. export type ConnectionOptions = ConnectOptions;
  2271. /* for ts-mongoose */
  2272. class mquery {}
  2273. }