index.d.ts 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813
  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. runValidators?: boolean;
  751. /** The session associated with this query. */
  752. session?: mongodb.ClientSession;
  753. setDefaultsOnInsert?: boolean;
  754. skip?: number;
  755. snapshot?: any;
  756. sort?: any;
  757. /** overwrites the schema's strict mode option */
  758. strict?: boolean | string;
  759. tailable?: number;
  760. /**
  761. * If set to `false` and schema-level timestamps are enabled,
  762. * skip timestamps for this update. Note that this allows you to overwrite
  763. * timestamps. Does nothing if schema-level timestamps are not set.
  764. */
  765. timestamps?: boolean;
  766. upsert?: boolean;
  767. useFindAndModify?: boolean;
  768. writeConcern?: any;
  769. }
  770. type MongooseQueryOptions = Pick<QueryOptions, 'populate' | 'lean' | 'omitUndefined' | 'strict' | 'useFindAndModify'>;
  771. interface SaveOptions {
  772. checkKeys?: boolean;
  773. j?: boolean;
  774. safe?: boolean | WriteConcern;
  775. session?: ClientSession | null;
  776. timestamps?: boolean;
  777. validateBeforeSave?: boolean;
  778. validateModifiedOnly?: boolean;
  779. w?: number | string;
  780. wtimeout?: number;
  781. }
  782. interface WriteConcern {
  783. j?: boolean;
  784. w?: number | 'majority' | TagSet;
  785. wtimeout?: number;
  786. }
  787. interface TagSet {
  788. [k: string]: string;
  789. }
  790. interface InsertManyOptions {
  791. limit?: number;
  792. rawResult?: boolean;
  793. ordered?: boolean;
  794. lean?: boolean;
  795. session?: mongodb.ClientSession;
  796. populate?: string | string[] | PopulateOptions | PopulateOptions[];
  797. }
  798. interface InsertManyResult extends mongodb.InsertWriteOpResult<any> {
  799. mongoose?: { validationErrors?: Array<Error.CastError | Error.ValidatorError> }
  800. }
  801. interface MapReduceOptions<T, Key, Val> {
  802. // eslint-disable-next-line @typescript-eslint/ban-types
  803. map: Function | string;
  804. reduce: (key: Key, vals: T[]) => Val;
  805. /** query filter object. */
  806. query?: any;
  807. /** sort input objects using this key */
  808. sort?: any;
  809. /** max number of documents */
  810. limit?: number;
  811. /** keep temporary data default: false */
  812. keeptemp?: boolean;
  813. /** finalize function */
  814. finalize?: (key: Key, val: Val) => Val;
  815. /** scope variables exposed to map/reduce/finalize during execution */
  816. scope?: any;
  817. /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */
  818. jsMode?: boolean;
  819. /** provide statistics on job execution time. default: false */
  820. verbose?: boolean;
  821. readPreference?: string;
  822. /** sets the output target for the map reduce job. default: {inline: 1} */
  823. out?: {
  824. /** the results are returned in an array */
  825. inline?: number;
  826. /**
  827. * {replace: 'collectionName'} add the results to collectionName: the
  828. * results replace the collection
  829. */
  830. replace?: string;
  831. /**
  832. * {reduce: 'collectionName'} add the results to collectionName: if
  833. * dups are detected, uses the reducer / finalize functions
  834. */
  835. reduce?: string;
  836. /**
  837. * {merge: 'collectionName'} add the results to collectionName: if
  838. * dups exist the new docs overwrite the old
  839. */
  840. merge?: string;
  841. };
  842. }
  843. interface GeoSearchOptions {
  844. /** x,y point to search for */
  845. near: number[];
  846. /** the maximum distance from the point near that a result can be */
  847. maxDistance: number;
  848. /** The maximum number of results to return */
  849. limit?: number;
  850. /** return the raw object instead of the Mongoose Model */
  851. lean?: boolean;
  852. }
  853. interface PopulateOptions {
  854. /** space delimited path(s) to populate */
  855. path: string;
  856. /** fields to select */
  857. select?: any;
  858. /** query conditions to match */
  859. match?: any;
  860. /** optional model to use for population */
  861. model?: string | Model<any>;
  862. /** optional query options like sort, limit, etc */
  863. options?: any;
  864. /** deep populate */
  865. populate?: PopulateOptions | Array<PopulateOptions>;
  866. /**
  867. * If true Mongoose will always set `path` to an array, if false Mongoose will
  868. * always set `path` to a document. Inferred from schema by default.
  869. */
  870. justOne?: boolean;
  871. /** transform function to call on every populated doc */
  872. transform?: (doc: any, id: any) => any;
  873. }
  874. interface ToObjectOptions {
  875. /** apply all getters (path and virtual getters) */
  876. getters?: boolean;
  877. /** apply virtual getters (can override getters option) */
  878. virtuals?: boolean;
  879. /** if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. */
  880. aliases?: boolean;
  881. /** remove empty objects (defaults to true) */
  882. minimize?: boolean;
  883. /** if set, mongoose will call this function to allow you to transform the returned object */
  884. transform?: (doc: any, ret: any, options: any) => any;
  885. /** if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. */
  886. depopulate?: boolean;
  887. /** if false, exclude the version key (`__v` by default) from the output */
  888. versionKey?: boolean;
  889. /** if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. */
  890. flattenMaps?: boolean;
  891. /** 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. */
  892. useProjection?: boolean;
  893. }
  894. type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init';
  895. type MongooseQueryMiddleware = 'count' | 'deleteMany' | 'deleteOne' | 'distinct' | 'find' | 'findOne' | 'findOneAndDelete' | 'findOneAndRemove' | 'findOneAndUpdate' | 'remove' | 'update' | 'updateOne' | 'updateMany';
  896. type SchemaPreOptions = { document?: boolean, query?: boolean };
  897. type SchemaPostOptions = { document?: boolean, query?: boolean };
  898. type ExtractQueryHelpers<M> = M extends Model<any, infer TQueryHelpers> ? TQueryHelpers : {};
  899. type ExtractMethods<M> = M extends Model<any, any, infer TMethods> ? TMethods : {};
  900. type PreMiddlewareFunction<T> = (this: T, next: (err?: CallbackError) => void) => void | Promise<void>;
  901. type PostMiddlewareFunction<ThisType, ResType = any> = (this: ThisType, res: ResType, next: (err?: CallbackError) => void) => void | Promise<void>;
  902. type ErrorHandlingMiddlewareFunction<ThisType, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: (err?: CallbackError) => void) => void;
  903. class Schema<DocType = Document, M extends Model<DocType, any, any> = Model<any, any, any>, SchemaDefinitionType = undefined> extends events.EventEmitter {
  904. /**
  905. * Create a new schema
  906. */
  907. constructor(definition?: SchemaDefinition<DocumentDefinition<SchemaDefinitionType>>, options?: SchemaOptions);
  908. /** Adds key path / schema type pairs to this schema. */
  909. add(obj: SchemaDefinition<DocumentDefinition<SchemaDefinitionType>> | Schema, prefix?: string): this;
  910. /**
  911. * Array of child schemas (from document arrays and single nested subdocs)
  912. * and their corresponding compiled models. Each element of the array is
  913. * an object with 2 properties: `schema` and `model`.
  914. */
  915. childSchemas: { schema: Schema, model: any }[];
  916. /** Returns a copy of this schema */
  917. clone(): Schema;
  918. /** Object containing discriminators defined on this schema */
  919. discriminators?: { [name: string]: Schema };
  920. /** Iterates the schemas paths similar to Array#forEach. */
  921. eachPath(fn: (path: string, type: SchemaType) => void): this;
  922. /** Defines an index (most likely compound) for this schema. */
  923. index(fields: any, options?: any): this;
  924. /**
  925. * Returns a list of indexes that this schema declares, via `schema.index()`
  926. * or by `index: true` in a path's options.
  927. */
  928. indexes(): Array<any>;
  929. /** Gets a schema option. */
  930. get(path: string): any;
  931. /**
  932. * 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),
  933. * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
  934. * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
  935. * [statics](http://mongoosejs.com/docs/guide.html#statics), and
  936. * [methods](http://mongoosejs.com/docs/guide.html#methods).
  937. */
  938. // eslint-disable-next-line @typescript-eslint/ban-types
  939. loadClass(model: Function, onlyVirtuals?: boolean): this;
  940. /** Adds an instance method to documents constructed from Models compiled from this schema. */
  941. // eslint-disable-next-line @typescript-eslint/ban-types
  942. method(name: string, fn: (this: EnforceDocument<DocType, ExtractMethods<M>>, ...args: any[]) => any, opts?: any): this;
  943. method(obj: { [name: string]: (this: EnforceDocument<DocType, ExtractMethods<M>>, ...args: any[]) => any }): this;
  944. /** Object of currently defined methods on this schema. */
  945. methods: { [name: string]: (this: EnforceDocument<DocType, ExtractMethods<M>>, ...args: any[]) => any };
  946. /** The original object passed to the schema constructor */
  947. obj: any;
  948. /** Gets/sets schema paths. */
  949. path(path: string): SchemaType;
  950. path(path: string, constructor: any): this;
  951. /** Lists all paths and their type in the schema. */
  952. paths: {
  953. [key: string]: SchemaType;
  954. }
  955. /** Returns the pathType of `path` for this schema. */
  956. pathType(path: string): string;
  957. /** Registers a plugin for this schema. */
  958. plugin(fn: (schema: Schema<DocType, Model<DocType>, SchemaDefinitionType>, opts?: any) => void, opts?: any): this;
  959. /** Defines a post hook for the model. */
  960. post<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T>): this;
  961. post<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
  962. post<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PostMiddlewareFunction<T>): this;
  963. post<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
  964. post<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction<T, Array<any>>): this;
  965. post<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, Array<any>>): this;
  966. post<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<T>): this;
  967. post<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
  968. post<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
  969. post<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
  970. post<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
  971. post<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
  972. post<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
  973. post<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
  974. post<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
  975. post<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
  976. /** Defines a pre hook for the model. */
  977. pre<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
  978. pre<T = EnforceDocument<DocType, ExtractMethods<M>>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
  979. pre<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PreMiddlewareFunction<T>): this;
  980. pre<T extends Query<any, any> = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
  981. pre<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction<T>): this;
  982. pre<T extends Aggregate<any> = Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
  983. pre<T extends Model<DocType> = M>(method: 'insertMany' | RegExp, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array<any>) => void | Promise<void>): this;
  984. 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;
  985. /** Object of currently defined query helpers on this schema. */
  986. 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 };
  987. /** Adds a method call to the queue. */
  988. queue(name: string, args: any[]): this;
  989. /** Removes the given `path` (or [`paths`]). */
  990. remove(paths: string | Array<string>): this;
  991. /** Returns an Array of path strings that are required by this schema. */
  992. requiredPaths(invalidate?: boolean): string[];
  993. /** Sets a schema option. */
  994. set(path: string, value: any, _tags?: any): this;
  995. /** Adds static "class" methods to Models compiled from this schema. */
  996. // eslint-disable-next-line @typescript-eslint/ban-types
  997. static(name: string, fn: (this: M, ...args: any[]) => any): this;
  998. // eslint-disable-next-line @typescript-eslint/ban-types
  999. static(obj: { [name: string]: (this: M, ...args: any[]) => any }): this;
  1000. /** Object of currently defined statics on this schema. */
  1001. statics: { [name: string]: (this: M, ...args: any[]) => any };
  1002. /** Creates a virtual type with the given name. */
  1003. virtual(name: string, options?: any): VirtualType;
  1004. /** Object of currently defined virtuals on this schema */
  1005. virtuals: any;
  1006. /** Returns the virtual type with the given `name`. */
  1007. virtualpath(name: string): VirtualType | null;
  1008. }
  1009. type SchemaDefinitionWithBuiltInClass<T extends number | string | boolean | Function> = T extends number
  1010. ? (typeof Number | 'number' | 'Number' | typeof Schema.Types.Number)
  1011. : T extends string
  1012. ? (typeof String | 'string' | 'String' | typeof Schema.Types.String)
  1013. : T extends boolean
  1014. ? (typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean)
  1015. : (Function | string);
  1016. type SchemaDefinitionProperty<T = undefined> = T extends string | number | Function
  1017. ? (SchemaDefinitionWithBuiltInClass<T> | SchemaTypeOptions<T>) :
  1018. SchemaTypeOptions<T extends undefined ? any : T> |
  1019. typeof SchemaType |
  1020. Schema<any> |
  1021. Schema<any>[] |
  1022. ReadonlyArray<Schema<any>> |
  1023. SchemaTypeOptions<T extends undefined ? any : T>[] |
  1024. ReadonlyArray<SchemaTypeOptions<T extends undefined ? any : T>> |
  1025. Function[] |
  1026. SchemaDefinition<T> |
  1027. SchemaDefinition<T>[] |
  1028. ReadonlyArray<SchemaDefinition<T>>;
  1029. type SchemaDefinition<T = undefined> = T extends undefined
  1030. ? { [path: string]: SchemaDefinitionProperty; }
  1031. : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
  1032. interface SchemaOptions {
  1033. /**
  1034. * By default, Mongoose's init() function creates all the indexes defined in your model's schema by
  1035. * calling Model.createIndexes() after you successfully connect to MongoDB. If you want to disable
  1036. * automatic index builds, you can set autoIndex to false.
  1037. */
  1038. autoIndex?: boolean;
  1039. /**
  1040. * If set to `true`, Mongoose will call Model.createCollection() to create the underlying collection
  1041. * in MongoDB if autoCreate is set to true. Calling createCollection() sets the collection's default
  1042. * collation based on the collation option and establishes the collection as a capped collection if
  1043. * you set the capped schema option.
  1044. */
  1045. autoCreate?: boolean;
  1046. /**
  1047. * By default, mongoose buffers commands when the connection goes down until the driver manages to reconnect.
  1048. * To disable buffering, set bufferCommands to false.
  1049. */
  1050. bufferCommands?: boolean;
  1051. /**
  1052. * If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before
  1053. * throwing an error. If not specified, Mongoose will use 10000 (10 seconds).
  1054. */
  1055. bufferTimeoutMS?: number;
  1056. /**
  1057. * Mongoose supports MongoDBs capped collections. To specify the underlying MongoDB collection be capped, set
  1058. * the capped option to the maximum size of the collection in bytes.
  1059. */
  1060. capped?: boolean | number | { size?: number; max?: number; autoIndexId?: boolean; };
  1061. /** Sets a default collation for every query and aggregation. */
  1062. collation?: mongodb.CollationDocument;
  1063. /**
  1064. * Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName
  1065. * method. This method pluralizes the name. Set this option if you need a different name for your collection.
  1066. */
  1067. collection?: string;
  1068. /**
  1069. * When you define a [discriminator](/docs/discriminators.html), Mongoose adds a path to your
  1070. * schema that stores which discriminator a document is an instance of. By default, Mongoose
  1071. * adds an `__t` path, but you can set `discriminatorKey` to overwrite this default.
  1072. */
  1073. discriminatorKey?: string;
  1074. /** defaults to false. */
  1075. emitIndexErrors?: boolean;
  1076. excludeIndexes?: any;
  1077. /**
  1078. * Mongoose assigns each of your schemas an id virtual getter by default which returns the document's _id field
  1079. * cast to a string, or in the case of ObjectIds, its hexString.
  1080. */
  1081. id?: boolean;
  1082. /**
  1083. * Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema
  1084. * constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior. If you
  1085. * don't want an _id added to your schema at all, you may disable it using this option.
  1086. */
  1087. _id?: boolean;
  1088. /**
  1089. * Mongoose will, by default, "minimize" schemas by removing empty objects. This behavior can be
  1090. * overridden by setting minimize option to false. It will then store empty objects.
  1091. */
  1092. minimize?: boolean;
  1093. /**
  1094. * Optimistic concurrency is a strategy to ensure the document you're updating didn't change between when you
  1095. * loaded it using find() or findOne(), and when you update it using save(). Set to `true` to enable
  1096. * optimistic concurrency.
  1097. */
  1098. optimisticConcurrency?: boolean;
  1099. /**
  1100. * Allows setting query#read options at the schema level, providing us a way to apply default ReadPreferences
  1101. * to all queries derived from a model.
  1102. */
  1103. read?: string;
  1104. /** Allows setting write concern at the schema level. */
  1105. writeConcern?: WriteConcern;
  1106. /** defaults to true. */
  1107. safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean };
  1108. /**
  1109. * The shardKey option is used when we have a sharded MongoDB architecture. Each sharded collection is
  1110. * given a shard key which must be present in all insert/update operations. We just need to set this
  1111. * schema option to the same shard key and we'll be all set.
  1112. */
  1113. shardKey?: Record<string, unknown>;
  1114. /**
  1115. * For backwards compatibility, the strict option does not apply to the filter parameter for queries.
  1116. * Mongoose has a separate strictQuery option to toggle strict mode for the filter parameter to queries.
  1117. */
  1118. strictQuery?: boolean | 'throw';
  1119. /**
  1120. * The strict option, (enabled by default), ensures that values passed to our model constructor that were not
  1121. * specified in our schema do not get saved to the db.
  1122. */
  1123. strict?: boolean | 'throw';
  1124. /** Exactly the same as the toObject option but only applies when the document's toJSON method is called. */
  1125. toJSON?: ToObjectOptions;
  1126. /**
  1127. * Documents have a toObject method which converts the mongoose document into a plain JavaScript object.
  1128. * This method accepts a few options. Instead of applying these options on a per-document basis, we may
  1129. * declare the options at the schema level and have them applied to all of the schema's documents by
  1130. * default.
  1131. */
  1132. toObject?: ToObjectOptions;
  1133. /**
  1134. * By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a
  1135. * type declaration. However, for applications like geoJSON, the 'type' property is important. If you want to
  1136. * control which key mongoose uses to find type declarations, set the 'typeKey' schema option.
  1137. */
  1138. typeKey?: string;
  1139. /**
  1140. * Write operations like update(), updateOne(), updateMany(), and findOneAndUpdate() only check the top-level
  1141. * schema's strict mode setting. Set to `true` to use the child schema's `strict` mode setting.
  1142. */
  1143. useNestedStrict?: boolean;
  1144. /** defaults to false */
  1145. usePushEach?: boolean;
  1146. /**
  1147. * By default, documents are automatically validated before they are saved to the database. This is to
  1148. * prevent saving an invalid document. If you want to handle validation manually, and be able to save
  1149. * objects which don't pass validation, you can set validateBeforeSave to false.
  1150. */
  1151. validateBeforeSave?: boolean;
  1152. /**
  1153. * The versionKey is a property set on each document when first created by Mongoose. This keys value
  1154. * contains the internal revision of the document. The versionKey option is a string that represents
  1155. * the path to use for versioning. The default is '__v'.
  1156. */
  1157. versionKey?: string | boolean;
  1158. /**
  1159. * By default, Mongoose will automatically select() any populated paths for you, unless you explicitly exclude them.
  1160. */
  1161. selectPopulatedPaths?: boolean;
  1162. /**
  1163. * skipVersioning allows excluding paths from versioning (i.e., the internal revision will not be
  1164. * incremented even if these paths are updated). DO NOT do this unless you know what you're doing.
  1165. * For subdocuments, include this on the parent document using the fully qualified path.
  1166. */
  1167. skipVersioning?: any;
  1168. /**
  1169. * Validation errors in a single nested schema are reported
  1170. * both on the child and on the parent schema.
  1171. * Set storeSubdocValidationError to false on the child schema
  1172. * to make Mongoose only report the parent error.
  1173. */
  1174. storeSubdocValidationError?: boolean;
  1175. /**
  1176. * The timestamps option tells mongoose to assign createdAt and updatedAt fields to your schema. The type
  1177. * assigned is Date. By default, the names of the fields are createdAt and updatedAt. Customize the
  1178. * field names by setting timestamps.createdAt and timestamps.updatedAt.
  1179. */
  1180. timestamps?: boolean | SchemaTimestampsConfig;
  1181. /**
  1182. * Determines whether a type set to a POJO becomes
  1183. * a Mixed path or a Subdocument (defaults to true).
  1184. */
  1185. typePojoToMixed?: boolean;
  1186. }
  1187. interface SchemaTimestampsConfig {
  1188. createdAt?: boolean | string;
  1189. updatedAt?: boolean | string;
  1190. currentTime?: () => (Date | number);
  1191. }
  1192. type Unpacked<T> = T extends (infer U)[] ? U : T;
  1193. export class SchemaTypeOptions<T> {
  1194. type?:
  1195. T extends string | number | boolean | Function ? SchemaDefinitionWithBuiltInClass<T> :
  1196. T extends Schema ? T :
  1197. T extends object[] ? (Schema<Document<Unpacked<T>>>[] | ReadonlyArray<Schema<Document<Unpacked<T>>>>) :
  1198. T extends string[] ? (SchemaDefinitionWithBuiltInClass<string>[] | ReadonlyArray<SchemaDefinitionWithBuiltInClass<string>>) :
  1199. T extends number[] ? (SchemaDefinitionWithBuiltInClass<number>[] | ReadonlyArray<SchemaDefinitionWithBuiltInClass<number>>) :
  1200. T extends boolean[] ? (SchemaDefinitionWithBuiltInClass<boolean>[] | ReadonlyArray<SchemaDefinitionWithBuiltInClass<boolean>>) :
  1201. T extends Function[] ? (SchemaDefinitionWithBuiltInClass<Function>[] | ReadonlyArray<SchemaDefinitionWithBuiltInClass<Function>>) :
  1202. T | typeof SchemaType | Schema;
  1203. /** Defines a virtual with the given name that gets/sets this path. */
  1204. alias?: string;
  1205. /** Function or object describing how to validate this schematype. See [validation docs](https://mongoosejs.com/docs/validation.html). */
  1206. // eslint-disable-next-line @typescript-eslint/ban-types
  1207. validate?: RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
  1208. /** Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message. */
  1209. cast?: string;
  1210. /**
  1211. * If true, attach a required validator to this path, which ensures this path
  1212. * path cannot be set to a nullish value. If a function, Mongoose calls the
  1213. * function and only checks for nullish values if the function returns a truthy value.
  1214. */
  1215. required?: boolean | (() => boolean) | [boolean, string] | [() => boolean, string];
  1216. /**
  1217. * The default value for this path. If a function, Mongoose executes the function
  1218. * and uses the return value as the default.
  1219. */
  1220. default?: T | ((this: any, doc: any) => T);
  1221. /**
  1222. * The model that `populate()` should use if populating this path.
  1223. */
  1224. ref?: string | Model<any> | ((this: any, doc: any) => string | Model<any>);
  1225. /**
  1226. * Whether to include or exclude this path by default when loading documents
  1227. * using `find()`, `findOne()`, etc.
  1228. */
  1229. select?: boolean | number;
  1230. /**
  1231. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
  1232. * build an index on this path when the model is compiled.
  1233. */
  1234. index?: boolean | number | IndexOptions | '2d' | '2dsphere' | 'hashed' | 'text';
  1235. /**
  1236. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose
  1237. * will build a unique index on this path when the
  1238. * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator).
  1239. */
  1240. unique?: boolean | number;
  1241. /**
  1242. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
  1243. * disallow changes to this path once the document is saved to the database for the first time. Read more
  1244. * about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html).
  1245. */
  1246. immutable?: boolean | ((this: any, doc: any) => boolean);
  1247. /**
  1248. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
  1249. * build a sparse index on this path.
  1250. */
  1251. sparse?: boolean | number;
  1252. /**
  1253. * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose
  1254. * will build a text index on this path.
  1255. */
  1256. text?: boolean | number | any;
  1257. /**
  1258. * Define a transform function for this individual schema type.
  1259. * Only called when calling `toJSON()` or `toObject()`.
  1260. */
  1261. transform?: (this: any, val: T) => any;
  1262. /** defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
  1263. get?: (value: T, schematype?: this) => any;
  1264. /** defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
  1265. set?: (value: T, schematype?: this) => any;
  1266. /** array of allowed values for this path. Allowed for strings, numbers, and arrays of strings */
  1267. enum?: Array<string | number | null> | ReadonlyArray<string | number | null> | { [path: string]: string | number | null };
  1268. /** The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths */
  1269. subtype?: number
  1270. /** The minimum value allowed for this path. Only allowed for numbers and dates. */
  1271. min?: number | Date | [number, string] | [Date, string] | readonly [number, string] | readonly [Date, string];
  1272. /** The maximum value allowed for this path. Only allowed for numbers and dates. */
  1273. max?: number | Date | [number, string] | [Date, string] | readonly [number, string] | readonly [Date, string];
  1274. /** Defines a TTL index on this path. Only allowed for dates. */
  1275. expires?: number | Date;
  1276. /** If `true`, Mongoose will skip gathering indexes on subpaths. Only allowed for subdocuments and subdocument arrays. */
  1277. excludeIndexes?: boolean;
  1278. /** If set, overrides the child schema's `_id` option. Only allowed for subdocuments and subdocument arrays. */
  1279. _id?: boolean;
  1280. /** If set, specifies the type of this map's values. Mongoose will cast this map's values to the given type. */
  1281. // eslint-disable-next-line @typescript-eslint/ban-types
  1282. of?: Function | SchemaTypeOptions<any>;
  1283. /** If true, uses Mongoose's default `_id` settings. Only allowed for ObjectIds */
  1284. auto?: boolean;
  1285. /** Attaches a validator that succeeds if the data string matches the given regular expression, and fails otherwise. */
  1286. match?: RegExp;
  1287. /** If truthy, Mongoose will add a custom setter that lowercases this string using JavaScript's built-in `String#toLowerCase()`. */
  1288. lowercase?: boolean;
  1289. /** If truthy, Mongoose will add a custom setter that removes leading and trailing whitespace using JavaScript's built-in `String#trim()`. */
  1290. trim?: boolean;
  1291. /** If truthy, Mongoose will add a custom setter that uppercases this string using JavaScript's built-in `String#toUpperCase()`. */
  1292. uppercase?: boolean;
  1293. /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at least the given number. */
  1294. minlength?: number | [number, string] | readonly [number, string];
  1295. /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at most the given number. */
  1296. maxlength?: number | [number, string] | readonly [number, string];
  1297. [other: string]: any;
  1298. }
  1299. export type RefType =
  1300. | number
  1301. | string
  1302. | Buffer
  1303. | undefined
  1304. | mongoose.Types.ObjectId
  1305. | mongoose.Types.Buffer
  1306. | typeof mongoose.Schema.Types.Number
  1307. | typeof mongoose.Schema.Types.String
  1308. | typeof mongoose.Schema.Types.Buffer
  1309. | typeof mongoose.Schema.Types.ObjectId;
  1310. /**
  1311. * Reference another Model
  1312. */
  1313. export type PopulatedDoc<
  1314. PopulatedType,
  1315. RawId extends RefType = (PopulatedType extends { _id?: RefType; } ? NonNullable<PopulatedType['_id']> : mongoose.Types.ObjectId) | undefined
  1316. > = PopulatedType | RawId;
  1317. interface IndexOptions {
  1318. background?: boolean,
  1319. expires?: number | string
  1320. sparse?: boolean,
  1321. type?: string,
  1322. unique?: boolean
  1323. }
  1324. interface ValidatorProps {
  1325. path: string;
  1326. value: any;
  1327. }
  1328. interface ValidatorMessageFn {
  1329. (props: ValidatorProps): string;
  1330. }
  1331. interface ValidateFn<T> {
  1332. (value: T): boolean;
  1333. }
  1334. interface LegacyAsyncValidateFn<T> {
  1335. (value: T, done: (result: boolean) => void): void;
  1336. }
  1337. interface AsyncValidateFn<T> {
  1338. (value: any): Promise<boolean>;
  1339. }
  1340. interface ValidateOpts<T> {
  1341. msg?: string;
  1342. message?: string | ValidatorMessageFn;
  1343. type?: string;
  1344. validator: ValidateFn<T> | LegacyAsyncValidateFn<T> | AsyncValidateFn<T>;
  1345. }
  1346. class VirtualType {
  1347. /** Applies getters to `value`. */
  1348. applyGetters(value: any, doc: Document): any;
  1349. /** Applies setters to `value`. */
  1350. applySetters(value: any, doc: Document): any;
  1351. /** Adds a custom getter to this virtual. */
  1352. // eslint-disable-next-line @typescript-eslint/ban-types
  1353. get(fn: Function): this;
  1354. /** Adds a custom setter to this virtual. */
  1355. // eslint-disable-next-line @typescript-eslint/ban-types
  1356. set(fn: Function): this;
  1357. }
  1358. namespace Schema {
  1359. namespace Types {
  1360. class Array extends SchemaType implements AcceptsDiscriminator {
  1361. /** This schema type's name, to defend against minifiers that mangle function names. */
  1362. static schemaName: string;
  1363. static options: { castNonArrays: boolean; };
  1364. discriminator<D extends Document>(name: string | number, schema: Schema<D>, value?: string): Model<D>;
  1365. discriminator<T extends Document, U extends Model<T>>(name: string | number, schema: Schema<T, U>, value?: string): U;
  1366. /**
  1367. * Adds an enum validator if this is an array of strings or numbers. Equivalent to
  1368. * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()`
  1369. */
  1370. enum(vals: string[] | number[]): this;
  1371. }
  1372. class Boolean extends SchemaType {
  1373. /** This schema type's name, to defend against minifiers that mangle function names. */
  1374. static schemaName: string;
  1375. /** Configure which values get casted to `true`. */
  1376. static convertToTrue: Set<any>;
  1377. /** Configure which values get casted to `false`. */
  1378. static convertToFalse: Set<any>;
  1379. }
  1380. class Buffer extends SchemaType {
  1381. /** This schema type's name, to defend against minifiers that mangle function names. */
  1382. static schemaName: string;
  1383. /**
  1384. * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/)
  1385. * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html).
  1386. */
  1387. subtype(subtype: number): this;
  1388. }
  1389. class Date extends SchemaType {
  1390. /** This schema type's name, to defend against minifiers that mangle function names. */
  1391. static schemaName: string;
  1392. /** Declares a TTL index (rounded to the nearest second) for _Date_ types only. */
  1393. expires(when: number | string): this;
  1394. /** Sets a maximum date validator. */
  1395. max(value: Date, message: string): this;
  1396. /** Sets a minimum date validator. */
  1397. min(value: Date, message: string): this;
  1398. }
  1399. class Decimal128 extends SchemaType {
  1400. /** This schema type's name, to defend against minifiers that mangle function names. */
  1401. static schemaName: string;
  1402. }
  1403. class DocumentArray extends SchemaType implements AcceptsDiscriminator {
  1404. /** This schema type's name, to defend against minifiers that mangle function names. */
  1405. static schemaName: string;
  1406. static options: { castNonArrays: boolean; };
  1407. discriminator<D extends Document>(name: string | number, schema: Schema<D>, value?: string): Model<D>;
  1408. discriminator<T extends Document, U extends Model<T>>(name: string | number, schema: Schema<T, U>, value?: string): U;
  1409. /** The schema used for documents in this array */
  1410. schema: Schema;
  1411. }
  1412. class Map extends SchemaType {
  1413. /** This schema type's name, to defend against minifiers that mangle function names. */
  1414. static schemaName: string;
  1415. }
  1416. class Mixed extends SchemaType {
  1417. /** This schema type's name, to defend against minifiers that mangle function names. */
  1418. static schemaName: string;
  1419. }
  1420. class Number extends SchemaType {
  1421. /** This schema type's name, to defend against minifiers that mangle function names. */
  1422. static schemaName: string;
  1423. /** Sets a enum validator */
  1424. enum(vals: number[]): this;
  1425. /** Sets a maximum number validator. */
  1426. max(value: number, message: string): this;
  1427. /** Sets a minimum number validator. */
  1428. min(value: number, message: string): this;
  1429. }
  1430. class ObjectId extends SchemaType {
  1431. /** This schema type's name, to defend against minifiers that mangle function names. */
  1432. static schemaName: string;
  1433. /** Adds an auto-generated ObjectId default if turnOn is true. */
  1434. auto(turnOn: boolean): this;
  1435. }
  1436. class Embedded extends SchemaType {
  1437. /** This schema type's name, to defend against minifiers that mangle function names. */
  1438. static schemaName: string;
  1439. /** The document's schema */
  1440. schema: Schema;
  1441. }
  1442. class String extends SchemaType {
  1443. /** This schema type's name, to defend against minifiers that mangle function names. */
  1444. static schemaName: string;
  1445. /** Adds an enum validator */
  1446. enum(vals: string[] | any): this;
  1447. /** Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
  1448. lowercase(shouldApply?: boolean): this;
  1449. /** Sets a regexp validator. */
  1450. match(value: RegExp, message: string): this;
  1451. /** Sets a maximum length validator. */
  1452. maxlength(value: number, message: string): this;
  1453. /** Sets a minimum length validator. */
  1454. minlength(value: number, message: string): this;
  1455. /** Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
  1456. trim(shouldTrim?: boolean): this;
  1457. /** Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
  1458. uppercase(shouldApply?: boolean): this;
  1459. }
  1460. }
  1461. }
  1462. namespace Types {
  1463. class Array<T> extends global.Array<T> {
  1464. /** Pops the array atomically at most one time per document `save()`. */
  1465. $pop(): T;
  1466. /** Atomically shifts the array at most one time per document `save()`. */
  1467. $shift(): T;
  1468. /** Adds values to the array if not already present. */
  1469. addToSet(...args: any[]): any[];
  1470. isMongooseArray: true;
  1471. /** Pushes items to the array non-atomically. */
  1472. nonAtomicPush(...args: any[]): number;
  1473. /** Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. */
  1474. push(...args: any[]): number;
  1475. /**
  1476. * Pulls items from the array atomically. Equality is determined by casting
  1477. * the provided value to an embedded document and comparing using
  1478. * [the `Document.equals()` function.](./api.html#document_Document-equals)
  1479. */
  1480. pull(...args: any[]): this;
  1481. /**
  1482. * Alias of [pull](#mongoosearray_MongooseArray-pull)
  1483. */
  1484. remove(...args: any[]): this;
  1485. /** Sets the casted `val` at index `i` and marks the array modified. */
  1486. set(i: number, val: T): this;
  1487. /** Atomically shifts the array at most one time per document `save()`. */
  1488. shift(): T;
  1489. /** Returns a native js Array. */
  1490. toObject(options?: ToObjectOptions): any;
  1491. toObject<T>(options?: ToObjectOptions): T;
  1492. /** Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. */
  1493. unshift(...args: any[]): number;
  1494. }
  1495. class Buffer extends global.Buffer {
  1496. /** Sets the subtype option and marks the buffer modified. */
  1497. subtype(subtype: number | ToObjectOptions): void;
  1498. /** Converts this buffer to its Binary type representation. */
  1499. toObject(subtype?: number): mongodb.Binary;
  1500. }
  1501. class Decimal128 extends mongodb.Decimal128 { }
  1502. class DocumentArray<T extends Document> extends Types.Array<T> {
  1503. /** DocumentArray constructor */
  1504. constructor(values: any[]);
  1505. isMongooseDocumentArray: true;
  1506. /** Creates a subdocument casted to this schema. */
  1507. create(obj: any): T;
  1508. /** Searches array items for the first document with a matching _id. */
  1509. id(id: any): T | null;
  1510. }
  1511. class EmbeddedDocument extends Document {
  1512. /** Returns the top level document of this sub-document. */
  1513. ownerDocument(): Document;
  1514. /** Returns this sub-documents parent document. */
  1515. parent(): Document;
  1516. /** Returns this sub-documents parent document. */
  1517. $parent(): Document;
  1518. /** Returns this sub-documents parent array. */
  1519. parentArray(): DocumentArray<Document>;
  1520. }
  1521. class Map<V> extends global.Map<string, V> {
  1522. /** Converts a Mongoose map into a vanilla JavaScript map. */
  1523. toObject(options?: ToObjectOptions & { flattenMaps?: boolean }): any;
  1524. }
  1525. const ObjectId: ObjectIdConstructor;
  1526. class _ObjectId extends mongodb.ObjectID {
  1527. _id?: ObjectId;
  1528. }
  1529. // Expose static methods of `mongodb.ObjectID` and allow calling without `new`
  1530. type ObjectIdConstructor = typeof _ObjectId & {
  1531. (val?: string | number): ObjectId;
  1532. };
  1533. // var objectId: mongoose.Types.ObjectId should reference mongodb.ObjectID not
  1534. // the ObjectIdConstructor, so we add the interface below
  1535. // eslint-disable-next-line @typescript-eslint/no-empty-interface
  1536. interface ObjectId extends mongodb.ObjectID { }
  1537. class Subdocument extends Document {
  1538. $isSingleNested: true;
  1539. /** Returns the top level document of this sub-document. */
  1540. ownerDocument(): Document;
  1541. /** Returns this sub-documents parent document. */
  1542. parent(): Document;
  1543. /** Returns this sub-documents parent document. */
  1544. $parent(): Document;
  1545. }
  1546. }
  1547. type ReturnsNewDoc = { new: true } | { returnOriginal: false };
  1548. type QueryWithHelpers<ResultType, DocType extends Document, THelpers = {}> = Query<ResultType, DocType, THelpers> & THelpers;
  1549. class Query<ResultType, DocType extends Document, THelpers = {}> {
  1550. _mongooseOptions: MongooseQueryOptions;
  1551. /**
  1552. * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
  1553. * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
  1554. * This is equivalent to calling `.cursor()` with no arguments.
  1555. */
  1556. [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
  1557. /** Executes the query */
  1558. exec(): Promise<ResultType>;
  1559. exec(callback?: (err: CallbackError, res: ResultType) => void): void;
  1560. // @todo: this doesn't seem right
  1561. exec(callback?: (err: any, result: ResultType) => void): Promise<ResultType> | any;
  1562. // eslint-disable-next-line @typescript-eslint/ban-types
  1563. $where(argument: string | Function): QueryWithHelpers<DocType[], DocType, THelpers>;
  1564. /** Specifies an `$all` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1565. all(val: Array<any>): this;
  1566. all(path: string, val: Array<any>): this;
  1567. /** Specifies arguments for an `$and` condition. */
  1568. and(array: FilterQuery<DocType>[]): this;
  1569. /** Specifies the batchSize option. */
  1570. batchSize(val: number): this;
  1571. /** Specifies a `$box` condition */
  1572. box(val: any): this;
  1573. box(lower: number[], upper: number[]): this;
  1574. cast(model: Model<any, THelpers> | null, obj: any): UpdateQuery<DocType>;
  1575. /**
  1576. * Executes the query returning a `Promise` which will be
  1577. * resolved with either the doc(s) or rejected with the error.
  1578. * Like `.then()`, but only takes a rejection handler.
  1579. */
  1580. catch: Promise<ResultType>['catch'];
  1581. /** Specifies a `$center` or `$centerSphere` condition. */
  1582. circle(area: any): this;
  1583. circle(path: string, area: any): this;
  1584. /** Adds a collation to this op (MongoDB 3.4 and up) */
  1585. collation(value: mongodb.CollationDocument): this;
  1586. /** Specifies the `comment` option. */
  1587. comment(val: string): this;
  1588. /** Specifies this query as a `count` query. */
  1589. count(callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1590. count(criteria: FilterQuery<DocType>, callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1591. /** Specifies this query as a `countDocuments` query. */
  1592. countDocuments(callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1593. countDocuments(criteria: FilterQuery<DocType>, callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1594. /**
  1595. * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
  1596. * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
  1597. */
  1598. cursor(options?: any): QueryCursor<DocType>;
  1599. /**
  1600. * Declare and/or execute this query as a `deleteMany()` operation. Works like
  1601. * remove, except it deletes _every_ document that matches `filter` in the
  1602. * collection, regardless of the value of `single`.
  1603. */
  1604. deleteMany(filter?: FilterQuery<DocType>, options?: QueryOptions, callback?: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1605. deleteMany(filter: FilterQuery<DocType>, callback: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1606. deleteMany(callback: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1607. /**
  1608. * Declare and/or execute this query as a `deleteOne()` operation. Works like
  1609. * remove, except it deletes at most one document regardless of the `single`
  1610. * option.
  1611. */
  1612. deleteOne(filter?: FilterQuery<DocType>, options?: QueryOptions, callback?: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1613. deleteOne(filter: FilterQuery<DocType>, callback: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1614. deleteOne(callback: (err: CallbackError, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1615. /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
  1616. distinct(field: string, filter?: FilterQuery<DocType>, callback?: (err: any, count: number) => void): QueryWithHelpers<Array<any>, DocType, THelpers>;
  1617. /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1618. // eslint-disable-next-line @typescript-eslint/ban-types
  1619. elemMatch(val: Function | any): this;
  1620. // eslint-disable-next-line @typescript-eslint/ban-types
  1621. elemMatch(path: string, val: Function | any): this;
  1622. /**
  1623. * Gets/sets the error flag on this query. If this flag is not null or
  1624. * undefined, the `exec()` promise will reject without executing.
  1625. */
  1626. error(): NativeError | null;
  1627. error(val: NativeError | null): this;
  1628. /** Specifies the complementary comparison value for paths specified with `where()` */
  1629. equals(val: any): this;
  1630. /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
  1631. estimatedDocumentCount(options?: QueryOptions, callback?: (err: any, count: number) => void): QueryWithHelpers<number, DocType, THelpers>;
  1632. /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1633. exists(val: boolean): this;
  1634. exists(path: string, val: boolean): this;
  1635. /**
  1636. * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
  1637. * which makes this query return detailed execution stats instead of the actual
  1638. * query result. This method is useful for determining what index your queries
  1639. * use.
  1640. */
  1641. explain(verbose?: string): this;
  1642. /** Creates a `find` query: gets a list of documents that match `filter`. */
  1643. find(callback?: (err: any, docs: DocType[]) => void): QueryWithHelpers<Array<DocType>, DocType, THelpers>;
  1644. find(filter: FilterQuery<DocType>, callback?: (err: any, docs: DocType[]) => void): QueryWithHelpers<Array<DocType>, DocType, THelpers>;
  1645. find(filter: FilterQuery<DocType>, projection?: any | null, options?: QueryOptions | null, callback?: (err: CallbackError, docs: DocType[]) => void): QueryWithHelpers<Array<DocType>, DocType, THelpers>;
  1646. /** Declares the query a findOne operation. When executed, the first found document is passed to the callback. */
  1647. findOne(filter?: FilterQuery<DocType>, projection?: any | null, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1648. /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
  1649. findOneAndDelete(filter?: FilterQuery<DocType>, options?: QueryOptions | null, callback?: (err: any, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1650. /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
  1651. findOneAndRemove(filter?: FilterQuery<DocType>, options?: QueryOptions | null, callback?: (err: any, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1652. /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
  1653. 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>;
  1654. 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>;
  1655. 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>;
  1656. /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
  1657. findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: any, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers>;
  1658. /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
  1659. 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>;
  1660. 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>;
  1661. 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>;
  1662. /** Specifies a `$geometry` condition */
  1663. geometry(object: { type: string, coordinates: any[] }): this;
  1664. /**
  1665. * For update operations, returns the value of a path in the update's `$set`.
  1666. * Useful for writing getters/setters that can work with both update operations
  1667. * and `save()`.
  1668. */
  1669. get(path: string): any;
  1670. /** Returns the current query filter (also known as conditions) as a POJO. */
  1671. getFilter(): FilterQuery<DocType>;
  1672. /** Gets query options. */
  1673. getOptions(): QueryOptions;
  1674. /** Gets a list of paths to be populated by this query */
  1675. getPopulatedPaths(): Array<string>;
  1676. /** Returns the current query filter. Equivalent to `getFilter()`. */
  1677. getQuery(): FilterQuery<DocType>;
  1678. /** Returns the current update operations as a JSON object. */
  1679. getUpdate(): UpdateQuery<DocType> | UpdateWithAggregationPipeline | null;
  1680. /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1681. gt(val: number): this;
  1682. gt(path: string, val: number): this;
  1683. /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1684. gte(val: number): this;
  1685. gte(path: string, val: number): this;
  1686. /** Sets query hints. */
  1687. hint(val: any): this;
  1688. /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1689. in(val: Array<any>): this;
  1690. in(path: string, val: Array<any>): this;
  1691. /** Declares an intersects query for `geometry()`. */
  1692. intersects(arg?: any): this;
  1693. /** Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. */
  1694. j(val: boolean | null): this;
  1695. /** Sets the lean option. */
  1696. lean<LeanResultType = LeanDocumentOrArray<ResultType>>(val?: boolean | any): QueryWithHelpers<LeanResultType, DocType, THelpers>;
  1697. /** Specifies the maximum number of documents the query will return. */
  1698. limit(val: number): this;
  1699. /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1700. lt(val: number): this;
  1701. lt(path: string, val: number): this;
  1702. /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1703. lte(val: number): this;
  1704. lte(path: string, val: number): this;
  1705. /**
  1706. * Runs a function `fn` and treats the return value of `fn` as the new value
  1707. * for the query to resolve to.
  1708. */
  1709. map<MappedType>(fn: (doc: DocType) => MappedType): QueryWithHelpers<MappedType, DocType, THelpers>;
  1710. /** Specifies an `$maxDistance` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1711. maxDistance(val: number): this;
  1712. maxDistance(path: string, val: number): this;
  1713. /** Specifies the maxScan option. */
  1714. maxScan(val: number): this;
  1715. /**
  1716. * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/)
  1717. * option. This will tell the MongoDB server to abort if the query or write op
  1718. * has been running for more than `ms` milliseconds.
  1719. */
  1720. maxTimeMS(ms: number): this;
  1721. /** Merges another Query or conditions object into this one. */
  1722. merge(source: Query<any, any> | FilterQuery<DocType>): this;
  1723. /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
  1724. mod(val: Array<number>): this;
  1725. mod(path: string, val: Array<number>): this;
  1726. /**
  1727. * Getter/setter around the current mongoose-specific options for this query
  1728. * Below are the current Mongoose-specific options.
  1729. */
  1730. mongooseOptions(val?: MongooseQueryOptions): MongooseQueryOptions;
  1731. /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1732. ne(val: any): this;
  1733. ne(path: string, val: any): this;
  1734. /** Specifies a `$near` or `$nearSphere` condition */
  1735. near(val: any): this;
  1736. near(path: string, val: any): this;
  1737. /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1738. nin(val: Array<any>): this;
  1739. nin(path: string, val: Array<any>): this;
  1740. /** Specifies arguments for an `$nor` condition. */
  1741. nor(array: Array<FilterQuery<DocType>>): this;
  1742. /** Specifies arguments for an `$or` condition. */
  1743. or(array: Array<FilterQuery<DocType>>): this;
  1744. /**
  1745. * Make this query throw an error if no documents match the given `filter`.
  1746. * This is handy for integrating with async/await, because `orFail()` saves you
  1747. * an extra `if` statement to check if no document was found.
  1748. */
  1749. orFail(err?: NativeError | (() => NativeError)): QueryWithHelpers<NonNullable<ResultType>, DocType, THelpers>;
  1750. /** Specifies a `$polygon` condition */
  1751. polygon(...coordinatePairs: number[][]): this;
  1752. polygon(path: string, ...coordinatePairs: number[][]): this;
  1753. /** Specifies paths which should be populated with other documents. */
  1754. populate(path: string | any, select?: string | any, model?: string | Model<any, THelpers>, match?: any): this;
  1755. populate(options: PopulateOptions | Array<PopulateOptions>): this;
  1756. /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */
  1757. projection(fields?: any | null): any;
  1758. /** Determines the MongoDB nodes from which to read. */
  1759. read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
  1760. /** Sets the readConcern option for the query. */
  1761. readConcern(level: string): this;
  1762. /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1763. regex(val: string | RegExp): this;
  1764. regex(path: string, val: string | RegExp): this;
  1765. /**
  1766. * Declare and/or execute this query as a remove() operation. `remove()` is
  1767. * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne)
  1768. * or [`deleteMany()`](#query_Query-deleteMany) instead.
  1769. */
  1770. remove(filter?: FilterQuery<DocType>, callback?: (err: CallbackError, res: mongodb.WriteOpResult['result']) => void): QueryWithHelpers<mongodb.WriteOpResult['result'], DocType, THelpers>;
  1771. /**
  1772. * Declare and/or execute this query as a replaceOne() operation. Same as
  1773. * `update()`, except MongoDB will replace the existing document and will
  1774. * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
  1775. */
  1776. replaceOne(filter?: FilterQuery<DocType>, replacement?: DocumentDefinition<DocType>, options?: QueryOptions | null, callback?: (err: any, res: any) => void): QueryWithHelpers<any, DocType, THelpers>;
  1777. /** Specifies which document fields to include or exclude (also known as the query "projection") */
  1778. select(arg: string | any): this;
  1779. /** Determines if field selection has been made. */
  1780. selected(): boolean;
  1781. /** Determines if exclusive field selection has been made. */
  1782. selectedExclusively(): boolean;
  1783. /** Determines if inclusive field selection has been made. */
  1784. selectedInclusively(): boolean;
  1785. /**
  1786. * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/)
  1787. * associated with this query. Sessions are how you mark a query as part of a
  1788. * [transaction](/docs/transactions.html).
  1789. */
  1790. session(session: mongodb.ClientSession | null): this;
  1791. /**
  1792. * Adds a `$set` to this query's update without changing the operation.
  1793. * This is useful for query middleware so you can add an update regardless
  1794. * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc.
  1795. */
  1796. set(path: string, value: any): this;
  1797. /** Sets query options. Some options only make sense for certain operations. */
  1798. setOptions(options: QueryOptions, overwrite?: boolean): this;
  1799. /** Sets the query conditions to the provided JSON object. */
  1800. setQuery(val: FilterQuery<DocType> | null): void;
  1801. setUpdate(update: UpdateQuery<DocType> | UpdateWithAggregationPipeline): void;
  1802. /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
  1803. size(val: number): this;
  1804. size(path: string, val: number): this;
  1805. /** Specifies the number of documents to skip. */
  1806. skip(val: number): this;
  1807. /** Specifies a `$slice` projection for an array. */
  1808. slice(val: number | Array<number>): this;
  1809. slice(path: string, val: number | Array<number>): this;
  1810. /** Specifies this query as a `snapshot` query. */
  1811. snapshot(val?: boolean): this;
  1812. /** Sets the sort order. If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. */
  1813. sort(arg: string | any): this;
  1814. /** Sets the tailable option (for use with capped collections). */
  1815. tailable(bool?: boolean, opts?: {
  1816. numberOfRetries?: number;
  1817. tailableRetryInterval?: number;
  1818. }): this;
  1819. /**
  1820. * Executes the query returning a `Promise` which will be
  1821. * resolved with either the doc(s) or rejected with the error.
  1822. */
  1823. then: Promise<ResultType>['then'];
  1824. /** Converts this query to a customized, reusable query constructor with all arguments and options retained. */
  1825. toConstructor(): new (...args: any[]) => QueryWithHelpers<ResultType, DocType, THelpers>;
  1826. /** Declare and/or execute this query as an update() operation. */
  1827. update(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: CallbackError, res: UpdateWriteOpResult) => void): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers>;
  1828. /**
  1829. * Declare and/or execute this query as an updateMany() operation. Same as
  1830. * `update()`, except MongoDB will update _all_ documents that match
  1831. * `filter` (as opposed to just the first one) regardless of the value of
  1832. * the `multi` option.
  1833. */
  1834. updateMany(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: CallbackError, res: UpdateWriteOpResult) => void): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers>;
  1835. /**
  1836. * Declare and/or execute this query as an updateOne() operation. Same as
  1837. * `update()`, except it does not support the `multi` or `overwrite` options.
  1838. */
  1839. updateOne(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: (err: CallbackError, res: UpdateWriteOpResult) => void): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers>;
  1840. /**
  1841. * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
  1842. * that must acknowledge this write before this write is considered successful.
  1843. */
  1844. w(val: string | number | null): this;
  1845. /** Specifies a path for use with chaining. */
  1846. where(path: string, val?: any): this;
  1847. where(obj: object): this;
  1848. where(): this;
  1849. /** Defines a `$within` or `$geoWithin` argument for geo-spatial queries. */
  1850. within(val?: any): this;
  1851. /**
  1852. * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to
  1853. * wait for this write to propagate through the replica set before this
  1854. * operation fails. The default is `0`, which means no timeout.
  1855. */
  1856. wtimeout(ms: number): this;
  1857. }
  1858. type _FilterQuery<T> = {
  1859. [P in keyof T]?: P extends '_id'
  1860. ? [Extract<T[P], mongodb.ObjectId>] extends [never]
  1861. ? mongodb.Condition<T[P]>
  1862. : mongodb.Condition<T[P] | string | { _id: mongodb.ObjectId }>
  1863. : [Extract<T[P], mongodb.ObjectId>] extends [never]
  1864. ? mongodb.Condition<T[P]>
  1865. : mongodb.Condition<T[P] | string>;
  1866. } &
  1867. mongodb.RootQuerySelector<T>;
  1868. export type FilterQuery<T> = _FilterQuery<DocumentDefinition<T>>;
  1869. type NumericTypes = number | mongodb.Decimal128 | mongodb.Double | mongodb.Int32 | mongodb.Long;
  1870. type KeysOfAType<TSchema, Type> = {
  1871. [key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? key : never;
  1872. }[keyof TSchema];
  1873. type PullOperator<TSchema> = {
  1874. [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?:
  1875. | Partial<Unpacked<TSchema[key]>>
  1876. | mongodb.ObjectQuerySelector<Unpacked<TSchema[key]>>
  1877. // Doesn't look like TypeScript has good support for creating an
  1878. // object containing dotted keys:
  1879. // https://stackoverflow.com/questions/58434389/typescript-deep-keyof-of-a-nested-object
  1880. | mongodb.QuerySelector<any>
  1881. | any;
  1882. } | any; // Because TS doesn't have good support for creating an object with dotted keys, including `.$.` re: #10075
  1883. /** @see https://docs.mongodb.com/manual/reference/operator/update */
  1884. type _UpdateQuery<TSchema> = {
  1885. /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
  1886. $currentDate?: mongodb.OnlyFieldsOfType<TSchema, NativeDate | mongodb.Timestamp, true | { $type: 'date' | 'timestamp' }> | any;
  1887. $inc?: mongodb.OnlyFieldsOfType<TSchema, NumericTypes | undefined> | any;
  1888. $min?: mongodb.MatchKeysAndValues<TSchema>;
  1889. $max?: mongodb.MatchKeysAndValues<TSchema>;
  1890. $mul?: mongodb.OnlyFieldsOfType<TSchema, NumericTypes | undefined> | any;
  1891. $rename?: { [key: string]: string };
  1892. $set?: mongodb.MatchKeysAndValues<TSchema>;
  1893. $setOnInsert?: mongodb.MatchKeysAndValues<TSchema>;
  1894. $unset?: mongodb.OnlyFieldsOfType<TSchema, any, any> | any;
  1895. /** @see https://docs.mongodb.com/manual/reference/operator/update-array/ */
  1896. $addToSet?: mongodb.SetFields<TSchema> | any;
  1897. $pop?: mongodb.OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1> | any;
  1898. $pull?: PullOperator<TSchema>;
  1899. $push?: mongodb.PushOperator<TSchema> | any;
  1900. $pullAll?: mongodb.PullAllOperator<TSchema> | any;
  1901. /** @see https://docs.mongodb.com/manual/reference/operator/update-bitwise/ */
  1902. $bit?: {
  1903. [key: string]: { [key in 'and' | 'or' | 'xor']?: number };
  1904. };
  1905. };
  1906. type UpdateWithAggregationPipeline = UpdateAggregationStage[];
  1907. type UpdateAggregationStage = { $addFields: any } |
  1908. { $set: any } |
  1909. { $project: any } |
  1910. { $unset: any } |
  1911. { $replaceRoot: any } |
  1912. { $replaceWith: any };
  1913. export type UpdateQuery<T> = (_UpdateQuery<DocumentDefinition<T>> & mongodb.MatchKeysAndValues<DocumentDefinition<T>>);
  1914. type _AllowStringsForIds<T> = {
  1915. [K in keyof T]: [Extract<T[K], mongodb.ObjectId>] extends [never] ? T[K] : T[K] | string;
  1916. };
  1917. export type DocumentDefinition<T> = _AllowStringsForIds<LeanDocument<T>>;
  1918. type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
  1919. type TreatAsPrimitives = actualPrimitives |
  1920. // eslint-disable-next-line no-undef
  1921. Date | RegExp | symbol | Error | BigInt | Types.ObjectId;
  1922. type LeanType<T> =
  1923. 0 extends (1 & T) ? T : // any
  1924. T extends TreatAsPrimitives ? T : // primitives
  1925. LeanDocument<T>; // Documents and everything else
  1926. export type _LeanDocument<T> = {
  1927. [K in keyof T]:
  1928. 0 extends (1 & T[K]) ? T[K] : // any
  1929. T[K] extends unknown[] ? LeanType<T[K][number]>[] : // Array
  1930. T[K] extends Document ? LeanDocument<T[K]> : // Subdocument
  1931. T[K];
  1932. };
  1933. export type LeanDocument<T> = Omit<_LeanDocument<T>, Exclude<keyof Document, '_id' | 'id' | '__v'> | '$isSingleNested'>;
  1934. export type LeanDocumentOrArray<T> = 0 extends (1 & T) ? T :
  1935. T extends unknown[] ? LeanDocument<T[number]>[] :
  1936. T extends Document ? LeanDocument<T> :
  1937. T;
  1938. class QueryCursor<DocType extends Document> extends stream.Readable {
  1939. [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
  1940. /**
  1941. * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
  1942. * Useful for setting the `noCursorTimeout` and `tailable` flags.
  1943. */
  1944. addCursorFlag(flag: string, value: boolean): this;
  1945. /**
  1946. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  1947. * `next()` will error.
  1948. */
  1949. close(): Promise<void>;
  1950. close(callback: (err: CallbackError) => void): void;
  1951. /**
  1952. * Execute `fn` for every document(s) in the cursor. If batchSize is provided
  1953. * `fn` will be executed for each batch of documents. If `fn` returns a promise,
  1954. * will wait for the promise to resolve before iterating on to the next one.
  1955. * Returns a promise that resolves when done.
  1956. */
  1957. eachAsync(fn: (doc: DocType) => any, options?: { parallel?: number }): Promise<void>;
  1958. eachAsync(fn: (doc: DocType[]) => any, options: { parallel?: number, batchSize: number }): Promise<void>;
  1959. eachAsync(fn: (doc: DocType) => any, options?: { parallel?: number, batchSize?: number }, cb?: (err: CallbackError) => void): void;
  1960. eachAsync(fn: (doc: DocType[]) => any, options: { parallel?: number, batchSize: number }, cb?: (err: CallbackError) => void): void;
  1961. /**
  1962. * Registers a transform function which subsequently maps documents retrieved
  1963. * via the streams interface or `.next()`
  1964. */
  1965. map<ResultType extends Document>(fn: (res: DocType) => ResultType): QueryCursor<ResultType>;
  1966. /**
  1967. * Get the next document from this cursor. Will return `null` when there are
  1968. * no documents left.
  1969. */
  1970. next(): Promise<DocType>;
  1971. next(callback: (err: CallbackError, doc: DocType | null) => void): void;
  1972. options: any;
  1973. }
  1974. class Aggregate<R> {
  1975. /**
  1976. * Sets an option on this aggregation. This function will be deprecated in a
  1977. * future release. */
  1978. addCursorFlag(flag: string, value: boolean): this;
  1979. /**
  1980. * Appends a new $addFields operator to this aggregate pipeline.
  1981. * Requires MongoDB v3.4+ to work
  1982. */
  1983. addFields(arg: any): this;
  1984. /** Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) */
  1985. allowDiskUse(value: boolean): this;
  1986. /** Appends new operators to this aggregate pipeline */
  1987. append(...args: any[]): this;
  1988. /**
  1989. * Executes the query returning a `Promise` which will be
  1990. * resolved with either the doc(s) or rejected with the error.
  1991. * Like [`.then()`](#query_Query-then), but only takes a rejection handler.
  1992. */
  1993. catch: Promise<R>['catch'];
  1994. /** Adds a collation. */
  1995. collation(options: mongodb.CollationDocument): this;
  1996. /** Appends a new $count operator to this aggregate pipeline. */
  1997. count(countName: string): this;
  1998. /**
  1999. * Sets the cursor option for the aggregation query (ignored for < 2.6.0).
  2000. */
  2001. cursor(options?: Record<string, unknown>): this;
  2002. /** Executes the aggregate pipeline on the currently bound Model. If cursor option is set, returns a cursor */
  2003. exec(callback?: (err: any, result: R) => void): Promise<R> | any;
  2004. /** Execute the aggregation with explain */
  2005. explain(callback?: (err: CallbackError, result: any) => void): Promise<any>;
  2006. /** Combines multiple aggregation pipelines. */
  2007. facet(options: any): this;
  2008. /** Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. */
  2009. graphLookup(options: any): this;
  2010. /** Appends new custom $group operator to this aggregate pipeline. */
  2011. group(arg: any): this;
  2012. /** Sets the hint option for the aggregation query (ignored for < 3.6.0) */
  2013. hint(value: Record<string, unknown> | string): this;
  2014. /**
  2015. * Appends a new $limit operator to this aggregate pipeline.
  2016. * @param num maximum number of records to pass to the next stage
  2017. */
  2018. limit(num: number): this;
  2019. /** Appends new custom $lookup operator to this aggregate pipeline. */
  2020. lookup(options: any): this;
  2021. /**
  2022. * Appends a new custom $match operator to this aggregate pipeline.
  2023. * @param arg $match operator contents
  2024. */
  2025. match(arg: any): this;
  2026. /**
  2027. * Binds this aggregate to a model.
  2028. * @param model the model to which the aggregate is to be bound
  2029. */
  2030. model(model: any): this;
  2031. /** Returns the current pipeline */
  2032. pipeline(): any[];
  2033. /** Appends a new $project operator to this aggregate pipeline. */
  2034. project(arg: string | Object): this;
  2035. /** Sets the readPreference option for the aggregation query. */
  2036. read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
  2037. /** Sets the readConcern level for the aggregation query. */
  2038. readConcern(level: string): this;
  2039. /** Appends a new $redact operator to this aggregate pipeline. */
  2040. redact(expression: any, thenExpr: string | any, elseExpr: string | any): this;
  2041. /** Appends a new $replaceRoot operator to this aggregate pipeline. */
  2042. replaceRoot(newRoot: object | string): this;
  2043. /**
  2044. * Helper for [Atlas Text Search](https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/)'s
  2045. * `$search` stage.
  2046. */
  2047. search(options: any): this;
  2048. /** Lets you set arbitrary options, for middleware or plugins. */
  2049. option(value: Record<string, unknown>): this;
  2050. /** Appends new custom $sample operator to this aggregate pipeline. */
  2051. sample(size: number): this;
  2052. /** Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html). */
  2053. session(session: mongodb.ClientSession | null): this;
  2054. /**
  2055. * Appends a new $skip operator to this aggregate pipeline.
  2056. * @param num number of records to skip before next stage
  2057. */
  2058. skip(num: number): this;
  2059. /** Appends a new $sort operator to this aggregate pipeline. */
  2060. sort(arg: any): this;
  2061. /** Provides promise for aggregate. */
  2062. then: Promise<R>['then'];
  2063. /**
  2064. * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name
  2065. * or a pipeline object.
  2066. */
  2067. sortByCount(arg: string | any): this;
  2068. /** Appends new custom $unwind operator(s) to this aggregate pipeline. */
  2069. unwind(...args: any[]): this;
  2070. }
  2071. class AggregationCursor extends stream.Readable {
  2072. /**
  2073. * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
  2074. * Useful for setting the `noCursorTimeout` and `tailable` flags.
  2075. */
  2076. addCursorFlag(flag: string, value: boolean): this;
  2077. /**
  2078. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  2079. * `next()` will error.
  2080. */
  2081. close(): Promise<void>;
  2082. close(callback: (err: CallbackError) => void): void;
  2083. /**
  2084. * Execute `fn` for every document(s) in the cursor. If batchSize is provided
  2085. * `fn` will be executed for each batch of documents. If `fn` returns a promise,
  2086. * will wait for the promise to resolve before iterating on to the next one.
  2087. * Returns a promise that resolves when done.
  2088. */
  2089. eachAsync(fn: (doc: any) => any, options?: { parallel?: number, batchSize?: number }): Promise<void>;
  2090. eachAsync(fn: (doc: any) => any, options?: { parallel?: number, batchSize?: number }, cb?: (err: CallbackError) => void): void;
  2091. /**
  2092. * Registers a transform function which subsequently maps documents retrieved
  2093. * via the streams interface or `.next()`
  2094. */
  2095. map(fn: (res: any) => any): this;
  2096. /**
  2097. * Get the next document from this cursor. Will return `null` when there are
  2098. * no documents left.
  2099. */
  2100. next(): Promise<any>;
  2101. next(callback: (err: CallbackError, doc: any) => void): void;
  2102. }
  2103. class SchemaType {
  2104. /** SchemaType constructor */
  2105. constructor(path: string, options?: any, instance?: string);
  2106. /** Get/set the function used to cast arbitrary values to this type. */
  2107. // eslint-disable-next-line @typescript-eslint/ban-types
  2108. static cast(caster?: Function | boolean): Function;
  2109. static checkRequired(checkRequired?: (v: any) => boolean): (v: any) => boolean;
  2110. /** Sets a default option for this schema type. */
  2111. static set(option: string, value: any): void;
  2112. /** Attaches a getter for all instances of this schema type. */
  2113. static get(getter: (value: any) => any): void;
  2114. /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */
  2115. OptionsConstructor: typeof SchemaTypeOptions;
  2116. /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
  2117. cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
  2118. /** Sets a default value for this SchemaType. */
  2119. default(val: any): any;
  2120. /** Adds a getter to this schematype. */
  2121. // eslint-disable-next-line @typescript-eslint/ban-types
  2122. get(fn: Function): this;
  2123. /**
  2124. * Defines this path as immutable. Mongoose prevents you from changing
  2125. * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew).
  2126. */
  2127. immutable(bool: boolean): this;
  2128. /** Declares the index options for this schematype. */
  2129. index(options: any): this;
  2130. /**
  2131. * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
  2132. * looks at to determine the foreign collection it should query.
  2133. */
  2134. ref(ref: string | boolean | Model<any>): this;
  2135. /**
  2136. * Adds a required validator to this SchemaType. The validator gets added
  2137. * to the front of this SchemaType's validators array using unshift().
  2138. */
  2139. required(required: boolean, message?: string): this;
  2140. /** Sets default select() behavior for this path. */
  2141. select(val: boolean): this;
  2142. /** Adds a setter to this schematype. */
  2143. // eslint-disable-next-line @typescript-eslint/ban-types
  2144. set(fn: Function): this;
  2145. /** Declares a sparse index. */
  2146. sparse(bool: boolean): this;
  2147. /** Declares a full text index. */
  2148. text(bool: boolean): this;
  2149. /** Defines a custom function for transforming this path when converting a document to JSON. */
  2150. transform(fn: (value: any) => any): this;
  2151. /** Declares an unique index. */
  2152. unique(bool: boolean): this;
  2153. /** Adds validator(s) for this document path. */
  2154. // eslint-disable-next-line @typescript-eslint/ban-types
  2155. validate(obj: RegExp | Function | any, errorMsg?: string,
  2156. type?: string): this;
  2157. }
  2158. class NativeError extends global.Error { }
  2159. type CallbackError = NativeError | null;
  2160. class Error extends global.Error {
  2161. constructor(msg: string);
  2162. /** The type of error. "MongooseError" for generic errors. */
  2163. name: string;
  2164. static messages: any;
  2165. static Messages: any;
  2166. }
  2167. namespace Error {
  2168. export class CastError extends Error {
  2169. name: 'CastError';
  2170. stringValue: string;
  2171. kind: string;
  2172. value: any;
  2173. path: string;
  2174. reason?: NativeError | null;
  2175. model?: any;
  2176. constructor(type: string, value: any, path: string, reason?: NativeError, schemaType?: SchemaType);
  2177. }
  2178. export class DisconnectedError extends Error {
  2179. name: 'DisconnectedError';
  2180. }
  2181. export class DivergentArrayError extends Error {
  2182. name: 'DivergentArrayError';
  2183. }
  2184. export class MissingSchemaError extends Error {
  2185. name: 'MissingSchemaError';
  2186. }
  2187. export class DocumentNotFoundError extends Error {
  2188. name: 'DocumentNotFoundError';
  2189. result: any;
  2190. numAffected: number;
  2191. filter: any;
  2192. query: any;
  2193. }
  2194. export class ObjectExpectedError extends Error {
  2195. name: 'ObjectExpectedError';
  2196. path: string;
  2197. }
  2198. export class ObjectParameterError extends Error {
  2199. name: 'ObjectParameterError';
  2200. }
  2201. export class OverwriteModelError extends Error {
  2202. name: 'OverwriteModelError';
  2203. }
  2204. export class ParallelSaveError extends Error {
  2205. name: 'ParallelSaveError';
  2206. }
  2207. export class ParallelValidateError extends Error {
  2208. name: 'ParallelValidateError';
  2209. }
  2210. export class MongooseServerSelectionError extends Error {
  2211. name: 'MongooseServerSelectionError';
  2212. }
  2213. export class StrictModeError extends Error {
  2214. name: 'StrictModeError';
  2215. isImmutableError: boolean;
  2216. path: string;
  2217. }
  2218. export class ValidationError extends Error {
  2219. name: 'ValidationError';
  2220. errors: { [path: string]: ValidatorError | CastError };
  2221. }
  2222. export class ValidatorError extends Error {
  2223. name: 'ValidatorError';
  2224. properties: {
  2225. message: string,
  2226. type?: string,
  2227. path?: string,
  2228. value?: any,
  2229. reason?: any
  2230. };
  2231. kind: string;
  2232. path: string;
  2233. value: any;
  2234. reason?: Error | null;
  2235. }
  2236. export class VersionError extends Error {
  2237. name: 'VersionError';
  2238. version: number;
  2239. modifiedPaths: Array<string>;
  2240. }
  2241. }
  2242. /** Deprecated types for backwards compatibility. */
  2243. /** Alias for QueryOptions for backwards compatability. */
  2244. type ModelUpdateOptions = QueryOptions;
  2245. type DocumentQuery<ResultType, DocType extends Document, THelpers = {}> = Query<ResultType, DocType, THelpers>;
  2246. /** Backwards support for DefinitelyTyped */
  2247. interface HookSyncCallback<T> {
  2248. (this: T, next: HookNextFunction, docs: any[]): Promise<any> | void;
  2249. }
  2250. interface HookAsyncCallback<T> {
  2251. (this: T, next: HookNextFunction, done: HookDoneFunction, docs: any[]): Promise<any> | void;
  2252. }
  2253. interface HookErrorCallback {
  2254. (error?: Error): any;
  2255. }
  2256. interface HookNextFunction {
  2257. (error?: Error): any;
  2258. }
  2259. interface HookDoneFunction {
  2260. (error?: Error): any;
  2261. }
  2262. export type SchemaTypeOpts<T> = SchemaTypeOptions<T>;
  2263. export type ConnectionOptions = ConnectOptions;
  2264. /* for ts-mongoose */
  2265. class mquery {}
  2266. }