UNPKG

154 kBTypeScriptView Raw
1// Type definitions for Mongoose 5.10.9
2// Project: http://mongoosejs.com/
3// Definitions by: horiuchi <https://github.com/horiuchi>
4// lukasz-zak <https://github.com/lukasz-zak>
5// jendrikw <https://github.com/jendrikw>
6// Ethan Resnick <https://github.com/ethanresnick>
7// vologa <https://github.com/vologab>
8// jussikinnula <https://github.com/jussikinnula>
9// ondratra <https://github.com/ondratra>
10// alfirin <https://github.com/alfirin>
11// Idan Dardikman <https://github.com/idandrd>
12// Dominik Heigl <https://github.com/various89>
13// Fazendaaa <https://github.com/Fazendaaa>
14// Norman Perrin <https://github.com/NormanPerrin>
15// stablio <https://github.com/stablio>
16// Emmanuel Gautier <https://github.com/emmanuelgautier>
17// Frontend Monster <https://github.com/frontendmonster>
18// Ming Chen <https://github.com/mingchen>
19// Olga Isakova <https://github.com/penumbra1>
20// HughKu <https://github.com/HughKu>
21// Erik Lopez <https://github.com/niuware>
22// Vlad Melnik <https://github.com/vladmel1234>
23// Jarom Loveridge <https://github.com/jloveridge>
24// Grimmer Kang <https://github.com/grimmer0125>
25// Richard Davison <https://github.com/richarddd>
26// Brian Chen <https://github.com/ToucheSir>
27// Boris Figovsky <https://github.com/borfig>
28// Simon Driscoll <https://github.com/dinodeSimon>
29// Anton Kenikh <https://github.com/anthony-kenikh>
30// Chathu Vishwajith <https://github.com/iamchathu>
31// LKHO <https://github.com/lkho>
32// Tom Yam <https://github.com/tomyam1>
33// Thomas Pischulski <https://github.com/nephix>
34// Sam Kim <https://github.com/rlaace423>
35// Dongjun Lee <https://github.com/ChazEpps>
36// Jan Nemcik <https://github.com/JanNemcik>
37// Cl3dson <https://github.com/cl3dson>
38// Richard Simko <https://github.com/richardsimko>
39// Marek Tuchalski <https://github.com/ith>
40// Jeremy Bensimon <https://github.com/jeremyben>
41// Andrei Alecu <https://github.com/andreialecu>
42// The Half Blood Prince <https://github.com/tHBp>
43// Pirasis Leelatanon <https://github.com/1pete>
44// Guillem Gelabert Sunyer <https://github.com/guillem-gelabert>
45// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
46// Minimum TypeScript Version: 3.2
47
48/// <reference types="mongodb" />
49/// <reference types="node" />
50
51
52/*
53 * Guidelines for maintaining these definitions:
54 * - If you spot an error here or there, please submit a PR.
55 * Give some examples/links to documentation if you can.
56 *
57 * For patches and minor releases:
58 * - Browse the changelog at https://github.com/Automattic/mongoose/blob/master/History.md
59 * and make necessary changes. Afterwards, update the version number at the top so we know
60 * which version we are on.
61 *
62 * For major releases:
63 * - Refer to the updated docs at https//mongoosejs.com/docs/api.html
64 * - On the left-hand side of the docs is a list of .js files. Reset and update the TODO list below
65 * then go through one-by-one, making any updates to params list, return type, etc. For documentation
66 * changes just copy/paste them into here.
67 * - Check the files off as you go. Some files below might not have anything in them. That's ok, this
68 * is just a simple heuristic to keep track of our progress.
69 */
70
71/*
72For easier searching, add a header to each section like so:
73To find a section, CTRL+F and type "section ___.js"
74/*
75 * section filename.js
76 * http://mongoosejs.com/docs/api.html#filename-js
77 */
78
79declare module "mongoose" {
80 import events = require('events');
81 import mongodb = require('mongodb');
82 import stream = require('stream');
83 import mongoose = require('mongoose');
84
85 // We can use TypeScript Omit once minimum required TypeScript Version is above 3.5
86 type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
87
88 type NonFunctionPropertyNames<T> = {
89 [K in keyof T]: T[K] extends Function ? never : K;
90 }[keyof T];
91
92 type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
93
94 type IfEquals<X, Y, A, B> =
95 (<T>() => T extends X ? 1 : 2) extends
96 (<T>() => T extends Y ? 1 : 2) ? A : B;
97
98 type ReadonlyKeysOf<T> = {
99 [P in keyof T]: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, never, P>
100 }[keyof T];
101
102 type OmitReadonly<T> = Omit<T, ReadonlyKeysOf<T>>;
103
104 type MongooseBuiltIns = mongodb.ObjectID | mongodb.Decimal128 | Date | number | boolean;
105
106 type ImplicitMongooseConversions<T> =
107 T extends MongooseBuiltIns
108 ? T extends (boolean | mongodb.Decimal128 | Date) ? T | string | number // accept numbers for these
109 : T | string
110 : T;
111
112 type DeepCreateObjectTransformer<T> =
113 T extends MongooseBuiltIns
114 ? T
115 : T extends object
116 ? { [V in keyof NonFunctionProperties<OmitReadonly<T>>]: T[V] extends object | undefined
117 ? ImplicitMongooseConversions<DeepCreateTransformer<NonNullable<T[V]>>>
118 : ImplicitMongooseConversions<T[V]> }
119 :
120 T;
121
122 // removes functions from schema from all levels
123 type DeepCreateTransformer<T> =
124 T extends Map<infer KM, infer KV>
125 // handle map values
126 // Maps are not scrubbed, replace below line with this once minimum TS version is 3.7:
127 // ? Map<KM, DeepNonFunctionProperties<KV>>
128 ? { [key: string]: DeepCreateTransformer<KV> } | [KM, KV][] | Map<KM, KV>
129 :
130 T extends Array<infer U>
131 ? Array<DeepCreateObjectTransformer<U>>
132 :
133 DeepCreateObjectTransformer<T>;
134
135 // mongoose allows Map<K, V> to be specified either as a Map or a Record<K, V>
136 type DeepMapAsObject<T> = T extends object | undefined
137 ? {
138 [K in keyof T]: T[K] extends Map<infer KM, infer KV> | undefined
139 // if it's a map, transform it into Map | Record
140 // only string keys allowed
141 ? KM extends string ? Map<KM, DeepMapAsObject<KV>> | Record<KM, DeepMapAsObject<KV>> | [KM, DeepMapAsObject<KV>][] : never
142 // otherwise if it's an object or undefined (for optional props), recursively go again
143 : T[K] extends object | undefined
144 ? DeepMapAsObject<T[K]>
145 : T[K]
146 }
147 : T;
148
149 /* Helper type to extract a definition type from a Document type */
150 type DocumentDefinition<T> = Omit<T, Exclude<keyof Document, '_id'>>;
151
152 type ScrubCreateDefinition<T> = DeepMapAsObject<DeepCreateTransformer<T>>
153
154 type CreateDocumentDefinition<T> = ScrubCreateDefinition<DocumentDefinition<T>>;
155
156 /**
157 * Patched version of FilterQuery to also allow:
158 * - documents, ObjectId and strings for `_id`
159 * - strings for properties defined as ObjectId
160 *
161 * Uses `[]` tuple syntax around the `Extract` to avoid distributing on unions.
162 * See: https://devblogs.microsoft.com/typescript/announcing-typescript-2-8-2/#conditional-types
163 *
164 * Negates the condition with `never`, because the following condition:
165 * Extract<T[P], mongodb.ObjectId> extends mongodb.ObjectId
166 * Would result in `never extends mongodb.ObjectId` for non-ObjectId properties,
167 * which would result in a passing conditional, because `never` is included in all types.
168 */
169 export type MongooseFilterQuery<T> = {
170 [P in keyof T]?: P extends '_id'
171 ? [Extract<T[P], mongodb.ObjectId>] extends [never]
172 ? mongodb.Condition<T[P]>
173 : mongodb.Condition<T[P] | string | { _id: mongodb.ObjectId }>
174 : [Extract<T[P], mongodb.ObjectId>] extends [never]
175 ? mongodb.Condition<T[P]>
176 : mongodb.Condition<T[P] | string>;
177 } &
178 mongodb.RootQuerySelector<T>;
179
180 /* FilterQuery alias type for using as type for filter/conditions parameters */
181 export type FilterQuery<T> = MongooseFilterQuery<DocumentDefinition<T>>;
182
183 /**
184 * Patched version of UpdateQuery to also allow:
185 * - setting attributes directly in the root, without a `$set` wrapper
186 * - setting attributes via dot-notation
187 */
188 export type MongooseUpdateQuery<S> = mongodb.UpdateQuery<S> & mongodb.MatchKeysAndValues<S>;
189
190 export type UpdateQuery<D> = MongooseUpdateQuery<DocumentDefinition<D>>;
191
192 // check whether a type consists just of {_id: T} and no other properties
193 type HasJustId<T> = keyof Omit<T, "_id"> extends never ? true : false;
194
195 // ensure that if an empty document type is passed, we allow any properties
196 // for backwards compatibility
197 export type CreateQuery<D> = HasJustId<CreateDocumentDefinition<D>> extends true
198 ? { _id?: any } & Record<string, any>
199 : D extends { _id: infer TId }
200 ? mongodb.OptionalId<CreateDocumentDefinition<D> & { _id: TId }>
201 : CreateDocumentDefinition<D>
202
203 /**
204 * Gets and optionally overwrites the function used to pluralize collection names
205 * @param fn function to use for pluralization of collection names
206 * @returns the current function used to pluralize collection names (defaults to the `mongoose-legacy-pluralize` module's function)
207 */
208 export function pluralize(fn?: (str: string) => string): (str: string) => string;
209
210 /*
211 * Some mongoose classes have the same name as the native JS classes
212 * Keep references to native classes using a "Native" prefix
213 */
214 class NativeBuffer extends global.Buffer { }
215 class NativeDate extends global.Date { }
216 class NativeError extends global.Error { }
217
218 /*
219 * section index.js
220 * http://mongoosejs.com/docs/api.html#index-js
221 */
222 export var DocumentProvider: any;
223 // recursive constructor
224 export var Mongoose: new (...args: any[]) => typeof mongoose;
225 type Mongoose = typeof mongoose;
226 export var SchemaTypes: typeof Schema.Types;
227
228 /** Expose connection states for user-land */
229 export var STATES: typeof ConnectionStates;
230 /** The default connection of the mongoose module. */
231 export var connection: Connection;
232 /** An array containing all connections associated with this Mongoose instance. */
233 export var connections: Connection[];
234 /** Models registred on the default mongoose connection. */
235 export var models: { [index: string]: Model<any> };
236 /** The node-mongodb-native driver Mongoose uses. */
237 export var mongo: typeof mongodb;
238 /** The Mongoose version */
239 export var version: string;
240
241 /**
242 * Opens the default mongoose connection.
243 * Options passed take precedence over options included in connection strings.
244 * @returns pseudo-promise wrapper around this
245 */
246 export function connect(uris: string, options: ConnectionOptions, callback: (err: mongodb.MongoError) => void): Promise<Mongoose>;
247 export function connect(uris: string, callback: (err: mongodb.MongoError) => void): Promise<Mongoose>;
248 export function connect(uris: string, options?: ConnectionOptions): Promise<Mongoose>;
249
250 /**
251 * Creates a Connection instance.
252 * Each connection instance maps to a single database. This method is helpful
253 * when mangaging multiple db connections.
254 * @param uri a mongodb:// URI
255 * @param options options to pass to the driver
256 * @returns the created Connection object
257 */
258 export function createConnection(): Connection;
259 export function createConnection(uri: string,
260 options?: ConnectionOptions
261 ): Connection & {
262 then: Promise<Connection>["then"];
263 catch: Promise<Connection>["catch"];
264 };
265
266 /**
267 * Disconnects all connections.
268 * @param fn called after all connection close.
269 */
270 export function disconnect(fn: (error?: any) => void): void;
271 /** Disconnects all connections. */
272 export function disconnect(): Promise<void>;
273
274 /** Gets mongoose options */
275 export function get(key: string): any;
276
277 /**
278 * Tests whether Mongoose can cast a value to an ObjectId
279 * @param value value to be tested if it can be cast to an ObjectId
280 */
281 export function isValidObjectId(value: any): boolean;
282
283 /**
284 * Defines a model or retrieves it.
285 * Models defined on the mongoose instance are available to all connection
286 * created by the same mongoose instance.
287 * @param name model name
288 * @param collection (optional, induced from model name)
289 * @param skipInit whether to skip initialization (defaults to false)
290 */
291 export function model<T extends Document>(name: string, schema?: Schema, collection?: string,
292 skipInit?: boolean): Model<T>;
293 export function model<T extends Document, U extends Model<T>>(
294 name: string,
295 schema?: Schema,
296 collection?: string,
297 skipInit?: boolean
298 ): U;
299
300 /**
301 * Removes the model named `name` from the default connection on this instance
302 * of Mongoose. You can use this function to clean up any models you created
303 * in your tests to prevent OverwriteModelErrors.
304 */
305 export function deleteModel(name: string | RegExp): Connection;
306
307 /**
308 * Returns an array of model names created on the default connection for this
309 * instance of Mongoose. Does not include names of models created
310 * on additional connections that were created with `createConnection()`.
311 */
312 export function modelNames(): string[];
313
314 /**
315 * Declares a global plugin executed on all Schemas.
316 * Equivalent to calling .plugin(fn) on each Schema you create.
317 * @param fn plugin callback
318 * @param opts optional options
319 */
320 export function plugin(fn: Function): typeof mongoose;
321 export function plugin<T>(fn: Function, opts: T): typeof mongoose;
322
323 /** Sets mongoose options */
324 export function set(key: string, value: any): void;
325
326 export function startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise<mongodb.ClientSession>;
327
328 export type CastError = Error.CastError;
329
330 /*
331 * section connection.js
332 * http://mongoosejs.com/docs/api.html#connection-js
333 *
334 * The Connection class exposed by require('mongoose')
335 * is actually the driver's NativeConnection class.
336 * connection.js defines a base class that the native
337 * versions extend. See:
338 * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js
339 */
340 abstract class ConnectionBase extends events.EventEmitter {
341 /**
342 * For practical reasons, a Connection equals a Db.
343 * @param base a mongoose instance
344 * @event connecting Emitted when connection.{open,openSet}() is executed on this connection.
345 * @event connected Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.
346 * @event open Emitted after we connected and onOpen is executed on all of this connections models.
347 * @event disconnecting Emitted when connection.close() was executed.
348 * @event disconnected Emitted after getting disconnected from the db.
349 * @event close Emitted after we disconnected and onClose executed on all of this connections models.
350 * @event reconnected Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.
351 * @event error Emitted when an error occurs on this connection.
352 * @event fullsetup Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.
353 * @event all Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
354 */
355 constructor(base: typeof mongoose);
356
357 /**
358 * Opens the connection to MongoDB.
359 * @param uri mongodb connection string
360 * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden.
361 * Mongoose defaults the server auto_reconnect options to true which can be overridden.
362 * See the node-mongodb-native driver instance for options that it understands.
363 * Options passed take precedence over options included in connection strings.
364 */
365 openUri(uri: string, options?: ConnectionOptions): Promise<Connection>;
366 openUri(uri: string, callback: (err: any, conn?: Connection) => void): Connection;
367 openUri(
368 uri: string,
369 options: ConnectionOptions,
370 callback?: (err: any, conn?: Connection) => void
371 ): Connection & {
372 then: Promise<Connection>["then"];
373 catch: Promise<Connection>["catch"];
374 };
375
376 /** Helper for dropDatabase() */
377 dropDatabase(callback?: (err: any) => void): Promise<any>;
378
379 /** Helper for creating a collection */
380 createCollection<T = any>(name: string, options?: mongodb.CollectionCreateOptions): Promise<mongodb.Collection<T>>;
381 createCollection<T = any>(name: string, cb: (err: any, collection: mongodb.Collection<T>) => void): Promise<void>;
382 createCollection<T = any>(name: string, options: mongodb.CollectionCreateOptions, cb?: (err: any, collection: mongodb.Collection) => void): Promise<mongodb.Collection<T>>;
383
384 /** Helper for dropCollection() */
385 dropCollection(name: string, callback?: (err: any) => void): Promise<void>;
386
387 /** Closes the connection */
388 close(callback?: (err: any) => void): Promise<void>;
389
390 /** Closes the connection */
391 close(force?: boolean, callback?: (err: any) => void): Promise<void>;
392
393 /**
394 * Retrieves a collection, creating it if not cached.
395 * Not typically needed by applications. Just talk to your collection through your model.
396 * @param name name of the collection
397 * @param options optional collection options
398 */
399 collection(name: string, options?: any): Collection;
400
401 /**
402 * Defines or retrieves a model.
403 * When no collection argument is passed, Mongoose produces a collection name by passing
404 * the model name to the utils.toCollectionName method. This method pluralizes the name.
405 * If you don't like this behavior, either pass a collection name or set your schemas
406 * collection name option.
407 * @param name the model name
408 * @param schema a schema. necessary when defining a model
409 * @param collection name of mongodb collection (optional) if not given it will be induced from model name
410 * @returns The compiled model
411 */
412 model<T extends Document>(name: string, schema?: Schema, collection?: string): Model<T>;
413 model<T extends Document, U extends Model<T>>(
414 name: string,
415 schema?: Schema,
416 collection?: string
417 ): U;
418
419 /**
420 * Removes the model named `name` from this connection, if it exists. You can
421 * use this function to clean up any models you created in your tests to
422 * prevent OverwriteModelErrors.
423 *
424 * @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
425 * @returns this
426 */
427 deleteModel(name: string | RegExp): Connection;
428
429 /** Returns an array of model names created on this connection. */
430 modelNames(): string[];
431
432 /** A hash of the global options that are associated with this connection */
433 config: Pick<ConnectionOptions, 'autoIndex' | 'autoCreate' | 'useCreateIndex' | 'useFindAndModify' | 'bufferCommands'>;
434
435 /** The mongodb.Db instance, set when the connection is opened */
436 db: mongodb.Db;
437
438 /** A hash of the collections associated with this connection */
439 collections: { [index: string]: Collection };
440
441 /** A hash of models registered with this connection */
442 models: { [index: string]: Model<any> };
443
444 /**
445 * Connection ready state
446 * 0 = disconnected
447 * 1 = connected
448 * 2 = connecting
449 * 3 = disconnecting
450 * Each state change emits its associated event name.
451 */
452 readyState: number;
453
454 /** Connected database name */
455 name: string
456
457 /** Connected host */
458 host: string
459
460 /** Connected port number */
461 port: number
462
463 /** mapping of ready states */
464 states: typeof ConnectionStates;
465 }
466
467 /**
468 * Connection optional settings.
469 *
470 * see
471 * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-connect
472 * and
473 * http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html
474 * for all available options.
475 *
476 */
477 interface ConnectionOptions extends mongodb.MongoClientOptions {
478 /** mongoose-specific options */
479 /** See https://mongoosejs.com/docs/guide.html#bufferCommands */
480 bufferCommands?: boolean;
481 /** database Name for Mongodb Atlas Connection */
482 dbName?: string;
483 /** passed to the connection db instance */
484 db?: any;
485 config?: {
486 /**
487 * set to false to disable automatic index creation for all
488 * models associated with this connection.
489 */
490 autoIndex?: boolean;
491 };
492 autoIndex?: boolean;
493
494 /** Before Mongoose builds indexes, it calls Model.createCollection()
495 * to create the underlying collection in MongoDB if autoCreate
496 * is set to true.(default: false) */
497 autoCreate?: boolean;
498
499
500 /** Configure csfle as especified in MongoDB official guide */
501 autoEncryption?: {
502 keyVaultNamespace: string,
503 kmsProviders: any,
504 schemaMap: any,
505 extraOptions?: any
506 }
507
508 /** Specify a journal write concern (default: false). */
509 journal?: boolean;
510
511 /** The current value of the parameter native_parser */
512 nativeParser?: boolean;
513
514 safe?: any;
515 slaveOk?: boolean;
516
517 /** username for authentication */
518 user?: string;
519 /** password for authentication */
520 pass?: string;
521
522 /** If true, this connection will use createIndex() instead of ensureIndex() for automatic index builds via Model.init(). */
523 useCreateIndex?: boolean;
524 /** See https://mongoosejs.com/docs/connections.html#use-mongo-client **/
525 useMongoClient?: boolean;
526 /** Flag for using new URL string parser instead of current (deprecated) one */
527 useNewUrlParser?: boolean;
528 /** Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify(). */
529 useFindAndModify?: boolean;
530 /** Flag for using new Server Discovery and Monitoring engine instead of current (deprecated) one */
531 useUnifiedTopology?: boolean;
532 /**
533 * With useUnifiedTopology, the MongoDB driver will try to find a server to send any given operation to,
534 * and keep retrying for serverSelectionTimeoutMS milliseconds.
535 * If not set, the MongoDB driver defaults to using 30000 (30 seconds).
536 */
537 serverSelectionTimeoutMS?: number;
538 /**
539 * With useUnifiedTopology, the MongoDB driver sends a heartbeat every heartbeatFrequencyMS to check on the status of the connection.
540 * A heartbeat is subject to serverSelectionTimeoutMS, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default.
541 * Mongoose only emits a 'disconnected' event after a heartbeat has failed,
542 * so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits 'disconnected'.
543 * We recommend you do not set this setting below 1000, too many heartbeats can lead to performance degradation.
544 */
545 heartbeatFrequencyMS?: number;
546
547 // Legacy properties - passed to the connection server instance(s)
548 mongos?: any;
549 server?: any;
550 replset?: any;
551 }
552
553 interface ClientSession extends mongodb.ClientSession { }
554
555 /*
556 * section drivers/node-mongodb-native/collection.js
557 * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js
558 */
559 var Collection: Collection;
560 interface Collection extends CollectionBase {
561 /**
562 * Collection constructor
563 * @param name name of the collection
564 * @param conn A MongooseConnection instance
565 * @param opts optional collection options
566 */
567 new(name: string, conn: Connection, opts?: any): Collection;
568 /** Formatter for debug print args */
569 $format(arg: any): string;
570 /** Debug print helper */
571 $print(name: any, i: any, args: any[]): void;
572 /** Retrieves information about this collections indexes. */
573 getIndexes(): any;
574 }
575
576 interface ConnectionUseDbOptions {
577 /**
578 * If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
579 */
580 useCache?: boolean;
581 }
582 /*
583 * section drivers/node-mongodb-native/connection.js
584 * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js
585 */
586 class Connection extends ConnectionBase {
587 /**
588 * Switches to a different database using the same connection pool.
589 * @param name The database name
590 * @param options Additional options
591 * @returns New Connection Object
592 */
593 useDb(name: string, options?: ConnectionUseDbOptions): Connection;
594
595 startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise<mongodb.ClientSession>;
596
597 /** Expose the possible connection states. */
598 static STATES: typeof ConnectionStates;
599 }
600
601 export enum ConnectionStates {
602 disconnected = 0,
603 connected = 1,
604 connecting = 2,
605 disconnecting = 3,
606 uninitialized = 99,
607 }
608
609 /*
610 * section error.js
611 * http://mongoosejs.com/docs/api.html#error-js
612 */
613 class Error extends global.Error {
614
615 // "MongooseError" for instances of the current class,
616 // an other string for instances of derived classes.
617 name: "MongooseError" | string;
618
619 /**
620 * MongooseError constructor
621 * @param msg Error message
622 */
623 constructor(msg: string);
624
625 /**
626 * The default built-in validator error messages. These may be customized.
627 * As you might have noticed, error messages support basic templating
628 * {PATH} is replaced with the invalid document path
629 * {VALUE} is replaced with the invalid value
630 * {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined"
631 * {MIN} is replaced with the declared min value for the Number.min validator
632 * {MAX} is replaced with the declared max value for the Number.max validator
633 */
634 static messages: any;
635
636 /** For backwards compatibility. Same as mongoose.Error.messages */
637 static Messages: any;
638
639 }
640
641 module Error {
642
643 /**
644 * section error/notFound.js
645 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DocumentNotFoundError
646 *
647 * An instance of this error class will be returned when `save()` fails
648 * because the underlying
649 * document was not found. The constructor takes one parameter, the
650 * conditions that mongoose passed to `update()` when trying to update
651 * the document.
652 */
653 export class DocumentNotFoundError extends Error {
654 name: 'DocumentNotFoundError';
655 filter: any;
656 query: any;
657 constructor(filter: any);
658 }
659
660 /**
661 * section error/cast.js
662 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError
663 *
664 * An instance of this error class will be returned when mongoose failed to
665 * cast a value.
666 */
667 export class CastError extends Error {
668 name: 'CastError';
669 stringValue: string;
670 kind: string;
671 value: any;
672 path: string;
673 reason?: any;
674 model?: any;
675
676 constructor(type: string, value: any, path: string, reason?: NativeError);
677
678 setModel(model: any): void;
679 }
680
681 /**
682 * section error/validation.js
683 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidationError
684
685 * An instance of this error class will be returned when [validation](/docs/validation.html) failed.
686 * The `errors` property contains an object whose keys are the paths that failed and whose values are
687 * instances of CastError or ValidationError.
688 *
689 */
690 export class ValidationError extends Error {
691 name: 'ValidationError';
692
693 errors: {[path: string]: ValidatorError | CastError};
694
695 constructor(instance?: MongooseDocument);
696
697 /** Console.log helper */
698 toString(): string;
699
700 inspect(): object;
701
702 toJSON(): object;
703
704 addError(path: string, error: any): void;
705 }
706
707 /**
708 * section error/validator.js
709 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidatorError
710 *
711 * A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances
712 */
713 export class ValidatorError extends Error {
714 name: 'ValidatorError';
715 properties: {message: string, type?: string, path?: string, value?: any, reason?: any};
716 kind: string;
717 path: string;
718 value: any;
719 reason: any;
720
721 constructor(properties: {message?: string, type?: string, path?: string, value?: any, reason?: any});
722
723 formatMessage(msg: string | Function, properties: any): string;
724
725 toString(): string;
726 }
727
728 /**
729 * section error/version.js
730 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.VersionError
731 *
732 * An instance of this error class will be returned when you call `save()` after
733 * the document in the database was changed in a potentially unsafe way. See
734 * the [`versionKey` option](http://mongoosejs.com/docs/guide.html#versionKey) for more information.
735 */
736 export class VersionError extends Error {
737 name: 'VersionError';
738 version: any;
739 modifiedPaths: Array<any>;
740
741 constructor(doc: MongooseDocument, currentVersion: any, modifiedPaths: any);
742 }
743
744 /**
745 * section error/parallelSave.js
746 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ParallelSaveError
747 *
748 * An instance of this error class will be returned when you call `save()` multiple
749 * times on the same document in parallel. See the [FAQ](http://mongoosejs.com/docs/faq.html) for more
750 * information.
751 */
752 export class ParallelSaveError extends Error {
753 name: 'ParallelSaveError';
754 constructor(doc: MongooseDocument);
755 }
756
757 /**
758 * section error/overwriteModel.js
759 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.OverwriteModelError
760 *
761 * Thrown when a model with the given name was already registered on the connection.
762 * See [the FAQ about `OverwriteModelError`](http://mongoosejs.com/docs/faq.html#overwrite-model-error).
763 */
764 export class OverwriteModelError extends Error {
765 name: 'OverwriteModelError';
766 constructor(name: string);
767 }
768
769 /**
770 * section error/missingSchema.js
771 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError
772 *
773 * Thrown when you try to access a model that has not been registered yet
774 */
775 export class MissingSchemaError extends Error {
776 name: 'MissingSchemaError';
777 constructor(name: string);
778 }
779
780 /**
781 * section error/divergentArray.js
782 * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DivergentArrayError
783 *
784 * An instance of this error will be returned if you used an array projection
785 * and then modified the array in an unsafe way.
786 */
787 export class DivergentArrayError extends Error {
788 name: 'DivergentArrayError';
789 constructor(paths: Array<any>);
790 }
791 }
792
793 interface EachAsyncOptions {
794 /** defaults to 1 */
795 parallel?: number;
796 }
797
798 /*
799 * section querycursor.js
800 * https://mongoosejs.com/docs/api.html#querycursor-js
801 *
802 * Callback signatures are from: https://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
803 * QueryCursor can only be accessed by query#cursor(), we only
804 * expose its interface to enable type-checking.
805 */
806 class QueryCursor<T extends Document> extends stream.Readable {
807 [Symbol.asyncIterator](): AsyncIterableIterator<T>;
808
809 /**
810 * A QueryCursor is a concurrency primitive for processing query results
811 * one document at a time. A QueryCursor fulfills the Node.js streams3 API,
812 * in addition to several other mechanisms for loading documents from MongoDB
813 * one at a time.
814 * Unless you're an advanced user, do not instantiate this class directly.
815 * Use Query#cursor() instead.
816 * @param options query options passed to .find()
817 * @event cursor Emitted when the cursor is created
818 * @event error Emitted when an error occurred
819 * @event data Emitted when the stream is flowing and the next doc is ready
820 * @event end Emitted when the stream is exhausted
821 */
822 constructor(query: Query<T>, options: any);
823
824 /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */
825 close(callback?: (error: any, result: any) => void): Promise<any>;
826
827 /**
828 * Execute fn for every document in the cursor. If fn returns a promise,
829 * will wait for the promise to resolve before iterating on to the next one.
830 * Returns a promise that resolves when done.
831 * @param fn Function to be executed for every document in the cursor
832 * @param callback Executed when all docs have been processed
833 */
834 eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise<T>;
835
836 /**
837 * Execute fn for every document in the cursor. If fn returns a promise,
838 * will wait for the promise to resolve before iterating on to the next one.
839 * Returns a promise that resolves when done.
840 * @param fn Function to be executed for every document in the cursor
841 * @param options Async options (e. g. parallel function execution)
842 * @param callback Executed when all docs have been processed
843 */
844 eachAsync(fn: (doc: T) => any, options: EachAsyncOptions, callback?: (err: any) => void): Promise<T>;
845
846 /**
847 * Registers a transform function which subsequently maps documents retrieved
848 * via the streams interface or .next()
849 */
850 map(fn: (doc: T) => T): this;
851
852 /**
853 * Get the next document from this cursor. Will return null when there are
854 * no documents left.
855 */
856 next(callback?: (err: any, doc?: T) => void): Promise<any>;
857 }
858
859 /*
860 * section virtualtype.js
861 * http://mongoosejs.com/docs/api.html#virtualtype-js
862 */
863 class VirtualType {
864 /** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */
865 constructor(options: any, name: string);
866 /** Applies getters to value using optional scope. */
867 applyGetters(value: any, scope: any): any;
868 /** Applies setters to value using optional scope. */
869 applySetters(value: any, scope: any): any;
870 /** Defines a getter. */
871 get(fn: Function): this;
872 /** Defines a setter. */
873 set(fn: Function): this;
874 }
875
876 interface HookOptions {
877 document?: boolean;
878 query?: boolean;
879 }
880
881 /*
882 * section schema.js
883 * http://mongoosejs.com/docs/api.html#schema-js
884 */
885 class Schema<T = any> extends events.EventEmitter {
886 /**
887 * Schema constructor.
888 * When nesting schemas, (children in the example above), always declare
889 * the child schema first before passing it into its parent.
890 * @event init Emitted after the schema is compiled into a Model.
891 */
892 constructor(definition?: SchemaDefinition, options?: SchemaOptions);
893
894 /** Adds key path / schema type pairs to this schema. */
895 add(obj: SchemaDefinition, prefix?: string): void;
896
897 /** Return a deep copy of this schema */
898 clone(): Schema;
899
900 /**
901 * Iterates the schemas paths similar to Array.forEach.
902 * @param fn callback function
903 * @returns this
904 */
905 eachPath(fn: (path: string, type: SchemaType) => void): this;
906
907 /**
908 * Gets a schema option.
909 * @param key option name
910 */
911 get(key: string): any;
912
913 /**
914 * Defines an index (most likely compound) for this schema.
915 * @param options Options to pass to MongoDB driver's createIndex() function
916 * @param options.expires Mongoose-specific syntactic sugar, uses ms to convert
917 * expires option into seconds for the expireAfterSeconds in the above link.
918 */
919 index(fields: any, options?: {
920 expires?: string;
921 [other: string]: any;
922 }): this;
923
924 /** Compiles indexes from fields and schema-level indexes */
925 indexes(): any[];
926
927 /**
928 * Loads an ES6 class into a schema. Maps setters + getters, static methods, and
929 * instance methods to schema virtuals, statics, and methods.
930 */
931 loadClass(model: Function): this;
932
933 /**
934 * Adds an instance method to documents constructed from Models compiled from this schema.
935 * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.
936 */
937 method<F extends keyof T>(method: F, fn: T[F]): this;
938 method(methodObj: {
939 [F in keyof T]: T[F]
940 }): this;
941
942 /**
943 * Gets/sets schema paths.
944 * Sets a path (if arity 2)
945 * Gets a path (if arity 1)
946 */
947 path(path: string): SchemaType;
948 path(path: string, constructor: any): this;
949
950 /**
951 * Returns the pathType of path for this schema.
952 * @returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
953 */
954 pathType(path: string): string;
955
956 /**
957 * Registers a plugin for this schema.
958 * @param plugin callback
959 */
960 plugin(plugin: (schema: Schema) => void): this;
961 plugin<T>(plugin: (schema: Schema, options: T) => void, opts: T): this;
962
963 /**
964 * Defines a post hook for the document
965 * Post hooks fire on the event emitted from document instances of Models compiled
966 * from this schema.
967 * @param method name of the method to hook
968 * @param fn callback
969 */
970 post<T extends Document>(method: 'insertMany', fn: (
971 this: Model<Document>,
972 error: mongodb.MongoError, docs: T[], next: (err?: NativeError) => void
973 ) => void): this;
974
975 post<T extends Document>(method: 'insertMany', fn: (
976 this: Model<Document>,
977 docs: T[], next: (err?: NativeError) => void
978 ) => void): this;
979
980 post<T extends Document>(method: 'insertMany', fn: (
981 this: Model<Document>,
982 docs: T[], next: (err?: NativeError) => Promise<any>
983 ) => void): this;
984
985 post<T extends Document>(method: 'remove' | 'deleteOne', { document, query }: HookOptions, fn: (
986 doc: T
987 ) => void): this;
988
989 post<T extends Document>(method: string | RegExp, fn: (
990 doc: T, next: (err?: NativeError) => void
991 ) => void): this;
992
993 post<T extends Document>(method: string | RegExp, fn: (
994 docs: T[], next: (err?: NativeError) => void
995 ) => void): this;
996
997 post<T extends Document>(method: string | RegExp, fn: (
998 docs: T[], next: (err?: NativeError) => void
999 ) => Promise<void>): this;
1000
1001 post<T extends Document>(method: string | RegExp, fn: (
1002 error: mongodb.MongoError, doc: T, next: (err?: NativeError) => void
1003 ) => void): this;
1004
1005 /**
1006 * Defines a pre hook for the document.
1007 */
1008 pre<T extends Document = Document>(
1009 method: "init" | "validate" | "save" | "remove",
1010 fn: HookSyncCallback<T>,
1011 errorCb?: HookErrorCallback
1012 ): this;
1013 pre<T extends Query<any> = Query<any>>(
1014 method:
1015 | "count"
1016 | "find"
1017 | "findOne"
1018 | "findOneAndRemove"
1019 | "findOneAndUpdate"
1020 | "update"
1021 | "updateOne"
1022 | "updateMany",
1023 fn: HookSyncCallback<T>,
1024 errorCb?: HookErrorCallback
1025 ): this;
1026 pre<T extends Aggregate<any> = Aggregate<any>>(
1027 method: "aggregate",
1028 fn: HookSyncCallback<T>,
1029 errorCb?: HookErrorCallback
1030 ): this;
1031 pre<T extends Model<Document> = Model<Document>>(
1032 method: "insertMany",
1033 fn: HookSyncCallback<T>,
1034 errorCb?: HookErrorCallback
1035 ): this;
1036 pre<T extends Document | Model<Document> | Query<any> | Aggregate<any>>(
1037 method: string | RegExp,
1038 fn: HookSyncCallback<T>,
1039 errorCb?: HookErrorCallback
1040 ): this;
1041
1042 pre<T extends Document = Document>(
1043 method: "init" | "validate" | "save" | "remove",
1044 parallel: boolean,
1045 fn: HookAsyncCallback<T>,
1046 errorCb?: HookErrorCallback
1047 ): this;
1048 pre<T extends Query<any> = Query<any>>(
1049 method:
1050 | "count"
1051 | "find"
1052 | "findOne"
1053 | "findOneAndRemove"
1054 | "findOneAndUpdate"
1055 | "update"
1056 | "updateOne"
1057 | "updateMany",
1058 parallel: boolean,
1059 fn: HookAsyncCallback<T>,
1060 errorCb?: HookErrorCallback
1061 ): this;
1062 pre<T extends Aggregate<any> = Aggregate<any>>(
1063 method: "aggregate",
1064 parallel: boolean,
1065 fn: HookAsyncCallback<T>,
1066 errorCb?: HookErrorCallback
1067 ): this;
1068 pre<T extends Model<Document> = Model<Document>>(
1069 method: "insertMany",
1070 parallel: boolean,
1071 fn: HookAsyncCallback<T>,
1072 errorCb?: HookErrorCallback
1073 ): this;
1074 pre<T extends Document | Model<Document> | Query<any> | Aggregate<any>>(
1075 method: string | RegExp,
1076 parallel: boolean,
1077 fn: HookAsyncCallback<T>,
1078 errorCb?: HookErrorCallback
1079 ): this;
1080
1081 /**
1082 * Adds a method call to the queue.
1083 * @param name name of the document method to call later
1084 * @param args arguments to pass to the method
1085 */
1086 queue(name: string, args: any[]): this;
1087
1088 /**
1089 * Removes the given path (or [paths]).
1090 */
1091 remove(path: string | string[]): void;
1092
1093 /**
1094 * @param invalidate refresh the cache
1095 * @returns an Array of path strings that are required by this schema.
1096 */
1097 requiredPaths(invalidate?: boolean): string[];
1098
1099 /**
1100 * Lists all paths and their type in the current schema.
1101 */
1102 paths: {
1103 [key: string]: SchemaType;
1104 }
1105
1106 /**
1107 * Sets/gets a schema option.
1108 * @param key option name
1109 * @param value if not passed, the current option value is returned
1110 */
1111 set<T extends keyof SchemaOptions>(key: T): SchemaOptions[T];
1112 set<T extends keyof SchemaOptions>(key: T, value: SchemaOptions[T]): this;
1113
1114 /**
1115 * Adds static "class" methods to Models compiled from this schema.
1116 */
1117 static(name: string, fn: Function): this;
1118 static(nameObj: { [name: string]: Function }): this;
1119
1120 /** Creates a virtual type with the given name. */
1121 virtual(name: string, options?: any): VirtualType;
1122
1123 /** Returns the virtual type with the given name. */
1124 virtualpath(name: string): VirtualType;
1125
1126 /** The allowed index types */
1127 static indexTypes: string[];
1128
1129 /**
1130 * Reserved document keys.
1131 * Keys in this object are names that are rejected in schema declarations
1132 * b/c they conflict with mongoose functionality. Using these key name
1133 * will throw an error.
1134 */
1135 static reserved: any;
1136
1137 /** Object of currently defined methods on this schema. */
1138 methods: {
1139 [F in keyof T]: T[F]
1140 };
1141 /** Object of currently defined statics on this schema. */
1142 statics: any;
1143 /** Object of currently defined query helpers on this schema. */
1144 query: any;
1145 /** The original object passed to the schema constructor */
1146 obj: any;
1147 }
1148
1149 // Hook functions: https://github.com/vkarpov15/hooks-fixed
1150 interface HookSyncCallback<T> {
1151 (this: T, next: HookNextFunction, docs: any[]): Promise<any> | void;
1152 }
1153
1154 interface HookAsyncCallback<T> {
1155 (this: T, next: HookNextFunction, done: HookDoneFunction, docs: any[]): Promise<any> | void;
1156 }
1157
1158 interface HookErrorCallback {
1159 (error?: Error): any;
1160 }
1161
1162 interface HookNextFunction {
1163 (error?: Error): any;
1164 }
1165
1166 interface HookDoneFunction {
1167 (error?: Error): any;
1168 }
1169
1170 interface SchemaOptions {
1171 /** defaults to false (which means use the connection's autoIndex option) */
1172 autoIndex?: boolean;
1173 /**
1174 * When false, use the connection's autoCreate option
1175 * @default false
1176 */
1177 autoCreate?: boolean;
1178 /** defaults to true */
1179 bufferCommands?: boolean;
1180 /** defaults to false */
1181 capped?: boolean | number | { size?: number; max?: number; autoIndexId?: boolean; };
1182 /** Sets a default collation for every query and aggregation. */
1183 collation?: CollationOptions;
1184 /** no default */
1185 collection?: string;
1186 /** defaults to "__t" */
1187 discriminatorKey?: string;
1188 /** defaults to false. */
1189 emitIndexErrors?: boolean;
1190 excludeIndexes?: any;
1191 /** defaults to true */
1192 id?: boolean;
1193 /** defaults to true */
1194 _id?: boolean;
1195 /** controls document#toObject behavior when called manually - defaults to true */
1196 minimize?: boolean;
1197 /** When true, mongoose will throw a Version Error if a document has changed before saving - defaults to false */
1198 optimisticConcurrency?: boolean;
1199 read?: string;
1200 writeConcern?: WriteConcern;
1201 /** defaults to true. */
1202 safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean };
1203
1204 /** defaults to null */
1205 shardKey?: object;
1206 /** no default */
1207 strictQuery?: boolean;
1208 /** defaults to true */
1209 strict?: boolean | "throw";
1210 /** no default */
1211 toJSON?: DocumentToObjectOptions;
1212 /** no default */
1213 toObject?: DocumentToObjectOptions;
1214 /** defaults to 'type' */
1215 typeKey?: string;
1216 /** defaults to false */
1217 useNestedStrict?: boolean;
1218 /** defaults to false */
1219 usePushEach?: boolean;
1220 /** defaults to true */
1221 validateBeforeSave?: boolean;
1222 /** defaults to "__v" */
1223 versionKey?: string | boolean;
1224 /**
1225 * By default, Mongoose will automatically
1226 * select() any populated paths.
1227 * To opt out, set selectPopulatedPaths to false.
1228 */
1229 selectPopulatedPaths?: boolean;
1230 /**
1231 * skipVersioning allows excluding paths from
1232 * versioning (the internal revision will not be
1233 * incremented even if these paths are updated).
1234 */
1235 skipVersioning?: any;
1236 /**
1237 * Validation errors in a single nested schema are reported
1238 * both on the child and on the parent schema.
1239 * Set storeSubdocValidationError to false on the child schema
1240 * to make Mongoose only report the parent error.
1241 */
1242 storeSubdocValidationError?: boolean;
1243 /**
1244 * If set timestamps, mongoose assigns createdAt
1245 * and updatedAt fields to your schema, the type
1246 * assigned is Date.
1247 */
1248 timestamps?: boolean | SchemaTimestampsConfig;
1249 /**
1250 * Determines whether a type set to a POJO becomes
1251 * a Mixed path or a Subdocument (defaults to true).
1252 */
1253 typePojoToMixed?:boolean;
1254 }
1255
1256 interface SchemaTimestampsConfig {
1257 createdAt?: boolean | string;
1258 updatedAt?: boolean | string;
1259 currentTime?: () => (Date | number);
1260 }
1261
1262 /*
1263 * Intellisense for Schema definitions
1264 */
1265 interface SchemaDefinition {
1266 [path: string]: SchemaTypeOpts<any> | Schema | SchemaType;
1267 }
1268
1269 /*
1270 * The standard options available when configuring a schema type:
1271 * new Schema({
1272 * name: {
1273 * type: String,
1274 * required: true,
1275 * ...
1276 * }
1277 * });
1278 *
1279 * Note: the properties have Object as a fallback type: | Object
1280 * because this interface does not apply to a schematype that
1281 * does not have a type property. Ex:
1282 * new Schema({
1283 * name: {
1284 * first: String, // since name does not have a "type" property
1285 * last: String // first and last can have any valid type
1286 * ...
1287 * }
1288 * });
1289 *
1290 * References:
1291 * - http://mongoosejs.com/docs/schematypes.html
1292 * - http://mongoosejs.com/docs/api.html#schema_Schema.Types
1293 */
1294 interface SchemaTypeOpts<T> {
1295 alias?: string;
1296
1297 /* Common Options for all schema types */
1298 type?: T;
1299
1300 /** Sets a default value for this SchemaType. */
1301 default?: SchemaTypeOpts.DefaultFn<T> | T;
1302
1303 /**
1304 * Getters allow you to transform the representation of the data as it travels
1305 * from the raw mongodb document to the value that you see.
1306 */
1307 get?: (value: T, schematype?: this) => T | any;
1308
1309 /** Declares the index options for this schematype. */
1310 index?: SchemaTypeOpts.IndexOpts | boolean | string;
1311
1312 /**
1313 * Adds a required validator to this SchemaType. The validator gets added
1314 * to the front of this SchemaType's validators array using unshift().
1315 */
1316 required?: SchemaTypeOpts.RequiredFn<T> |
1317 boolean | [boolean, string] |
1318 string | [string, string] |
1319 any;
1320
1321 /**
1322 * Sets default select() behavior for this path.
1323 * Set to true if this path should always be included in the results, false
1324 * if it should be excluded by default. This setting can be overridden at
1325 * the query level.
1326 */
1327 select?: boolean | any;
1328
1329 /**
1330 * Setters allow you to transform the data before it gets to the raw mongodb
1331 * document and is set as a value on an actual key.
1332 */
1333 set?: (value: T, schematype?: this) => T | any;
1334
1335 /** Declares a sparse index. */
1336 sparse?: boolean | any;
1337
1338 /** Declares a full text index. */
1339 text?: boolean | any;
1340
1341 /**
1342 * Adds validator(s) for this document path.
1343 * Validators always receive the value to validate as their first argument
1344 * and must return Boolean. Returning false means validation failed.
1345 */
1346 validate?: RegExp | [RegExp, string] |
1347 SchemaTypeOpts.ValidateFn<T> | [SchemaTypeOpts.ValidateFn<T>, string] |
1348 SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts |
1349 SchemaTypeOpts.AsyncPromiseValidationFn<T> | [SchemaTypeOpts.AsyncPromiseValidationFn<T>, string] |
1350 SchemaTypeOpts.AsyncPromiseValidationOpts |
1351 (SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts |
1352 SchemaTypeOpts.AsyncPromiseValidationFn<T> | SchemaTypeOpts.AsyncPromiseValidationOpts)[];
1353
1354 /** Declares an unique index. */
1355 unique?: boolean | any;
1356
1357
1358 /* Options for specific schema types (String, Number, Date, etc.) */
1359 /** String only - Adds an enum validator */
1360 enum?: T[] | SchemaTypeOpts.EnumOpts<T> | any;
1361 /** String only - Adds a lowercase setter. */
1362 lowercase?: boolean | any;
1363 /** String only - Sets a regexp validator. */
1364 match?: RegExp | [RegExp, string] | any;
1365 /** String only - Sets a maximum length validator. */
1366 maxlength?: number | [number, string] | any;
1367 /** String only - Sets a minimum length validator. */
1368 minlength?: number | [number, string] | any;
1369 /** String only - Adds a trim setter. */
1370 trim?: boolean | any;
1371 /** String only - Adds an uppercase setter. */
1372 uppercase?: boolean | any;
1373
1374 /**
1375 * Date, Number only - Sets a minimum number validator.
1376 * Sets a minimum date validator.
1377 */
1378 min?: number | [number, string] |
1379 Date | [Date, string] |
1380 any;
1381
1382 /**
1383 * Date, Number only - Sets a maximum number validator.
1384 * Sets a maximum date validator.
1385 */
1386 max?: number | [number, string] |
1387 Date | [Date, string] |
1388 any;
1389
1390 /**
1391 * Date only - Declares a TTL index (rounded to the nearest second)
1392 * for Date types only.
1393 */
1394 expires?: number | string | any;
1395
1396 /** ObjectId only - Adds an auto-generated ObjectId default if turnOn is true. */
1397 auto?: boolean | any;
1398
1399 /** Map only - Specifies the type of the map's attributes */
1400 of?: any;
1401
1402 [other: string]: any;
1403 }
1404
1405 // Interfaces specific to schema type options should be scoped in this namespace
1406 namespace SchemaTypeOpts {
1407 interface DefaultFn<T> {
1408 (...args: any[]): T;
1409 }
1410
1411 interface RequiredFn<T> {
1412 (required: boolean, message?: string): T;
1413 }
1414
1415 interface ValidateFn<T> {
1416 (value: T): boolean;
1417 }
1418
1419 interface AsyncValidateFn<T> {
1420 (value: T, done: (result: boolean) => void): void;
1421 }
1422
1423 interface ValidatorProps {
1424 path: string;
1425 value: any;
1426 }
1427
1428 interface ValidatorMessageFn {
1429 (props: ValidatorProps): string;
1430 }
1431
1432 interface ValidateOptsBase {
1433 msg?: string;
1434 message?: string | ValidatorMessageFn;
1435 type?: string;
1436 }
1437
1438 interface ValidateOpts extends ValidateOptsBase {
1439 /** deprecated */
1440 isAsync?: false;
1441 validator?: RegExp | ValidateFn<any>;
1442 }
1443
1444 interface AsyncValidateOpts extends ValidateOptsBase {
1445 /** deprecated */
1446 isAsync: true;
1447 validator: AsyncValidateFn<any>;
1448 }
1449
1450 interface AsyncPromiseValidationFn<T> {
1451 (value: T): Promise<boolean>;
1452 }
1453
1454 interface AsyncPromiseValidationOpts extends ValidateOptsBase {
1455 validator: AsyncPromiseValidationFn<any>;
1456 }
1457
1458 interface EnumOpts<T> {
1459 values?: T[];
1460 message?: string;
1461 }
1462
1463 interface IndexOpts {
1464 background?: boolean,
1465 expires?: number | string
1466 sparse?: boolean,
1467 type?: string,
1468 unique?: boolean,
1469 }
1470 }
1471
1472 /*
1473 * section document.js
1474 * http://mongoosejs.com/docs/api.html#document-js
1475 */
1476 interface MongooseDocument extends MongooseDocumentOptionals { }
1477 class MongooseDocument {
1478 /** Checks if a path is set to its default. */
1479 $isDefault(path?: string): boolean;
1480
1481 /** Getter/setter around the session associated with this document. */
1482 $session(session?: ClientSession): ClientSession;
1483
1484 /**
1485 * Takes a populated field and returns it to its unpopulated state.
1486 * If the path was not populated, this is a no-op.
1487 */
1488 depopulate(path?: string): this;
1489
1490 /**
1491 * Returns true if the Document stores the same data as doc.
1492 * Documents are considered equal when they have matching _ids, unless neither document
1493 * has an _id, in which case this function falls back to usin deepEqual().
1494 * @param doc a document to compare
1495 */
1496 equals(doc: MongooseDocument): boolean;
1497
1498 /**
1499 * Explicitly executes population and returns a promise.
1500 * Useful for ES2015 integration.
1501 * @returns promise that resolves to the document when population is done
1502 */
1503 execPopulate(): Promise<this>;
1504
1505 /** Checks if path was explicitly selected. If no projection, always returns true. */
1506 isDirectSelected(path: string): boolean;
1507
1508 /**
1509 * Returns the value of a path.
1510 * @param type optionally specify a type for on-the-fly attributes
1511 * @param options
1512 * @param options.virtuals apply virtuals before getting this path
1513 * @param options.getters if false, skip applying getters and just get the raw value
1514 */
1515 get(path: string, type?: any, options?: {
1516 virtuals?: boolean;
1517 getters?: boolean;
1518 }): any;
1519
1520 /**
1521 * Initializes the document without setters or marking anything modified.
1522 * Called internally after a document is returned from mongodb.
1523 * @param doc document returned by mongo
1524 * @param opts Options
1525 */
1526 init(doc: MongooseDocument, opts?: any): this;
1527
1528 /** Helper for console.log */
1529 inspect(options?: any): any;
1530
1531 /**
1532 * Marks a path as invalid, causing validation to fail.
1533 * The errorMsg argument will become the message of the ValidationError.
1534 * The value argument (if passed) will be available through the ValidationError.value property.
1535 * @param path the field to invalidate
1536 * @param errorMsg the error which states the reason path was invalid
1537 * @param value optional invalid value
1538 * @param kind optional kind property for the error
1539 * @returns the current ValidationError, with all currently invalidated paths
1540 */
1541 invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): Error.ValidationError | boolean;
1542
1543 /** Returns true if path was directly set and modified, else false. */
1544 isDirectModified(path: string): boolean;
1545
1546 /** Checks if path was initialized */
1547 isInit(path: string): boolean;
1548
1549 /**
1550 * Returns true if this document was modified, else false.
1551 * If path is given, checks if a path or any full path containing path as part of its path
1552 * chain has been modified.
1553 */
1554 isModified(path?: string): boolean;
1555
1556 /** Checks if path was selected in the source query which initialized this document. */
1557 isSelected(path: string): boolean;
1558
1559 /**
1560 * Marks the path as having pending changes to write to the db.
1561 * Very helpful when using Mixed types.
1562 * @param path the path to mark modified
1563 */
1564 markModified(path: string): void;
1565
1566 /** Returns the list of paths that have been modified. */
1567 modifiedPaths(): string[];
1568
1569 /**
1570 * Populates document references, executing the callback when complete.
1571 * If you want to use promises instead, use this function with
1572 * execPopulate()
1573 * Population does not occur unless a callback is passed or you explicitly
1574 * call execPopulate(). Passing the same path a second time will overwrite
1575 * the previous path options. See Model.populate() for explaination of options.
1576 * @param path The path to populate or an options object
1577 * @param names The properties to fetch from the populated document
1578 * @param callback When passed, population is invoked
1579 */
1580 populate(callback: (err: any, res: this) => void): this;
1581 populate(path: string, callback?: (err: any, res: this) => void): this;
1582 populate(path: string, names: string, callback?: (err: any, res: this) => void): this;
1583 populate(options: ModelPopulateOptions | ModelPopulateOptions[], callback?: (err: any, res: this) => void): this;
1584
1585 /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */
1586 populated(path: string): any;
1587
1588 /**
1589 * Sets the value of a path, or many paths.
1590 * @param path path or object of key/vals to set
1591 * @param val the value to set
1592 * @param type optionally specify a type for "on-the-fly" attributes
1593 * @param options optionally specify options that modify the behavior of the set
1594 */
1595 set(path: string, val: any, options?: any): this;
1596 set(path: string, val: any, type: any, options?: any): this;
1597 set(value: any): this;
1598
1599 /**
1600 * Overwrite all values, except for immutable properties.
1601 * @param obj the object to overwrite this document with
1602 */
1603 overwrite(obj: any): this;
1604
1605 /**
1606 * The return value of this method is used in calls to JSON.stringify(doc).
1607 * This method accepts the same options as Document#toObject. To apply the
1608 * options to every document of your schema by default, set your schemas
1609 * toJSON option to the same argument.
1610 */
1611 toJSON(options?: DocumentToObjectOptions): any;
1612
1613 /**
1614 * Converts this document into a plain javascript object, ready for storage in MongoDB.
1615 * Buffers are converted to instances of mongodb.Binary for proper storage.
1616 */
1617 toObject(options?: DocumentToObjectOptions): any;
1618
1619 /** Helper for console.log */
1620 toString(): string;
1621
1622 /**
1623 * Clears the modified state on the specified path.
1624 * @param path the path to unmark modified
1625 */
1626 unmarkModified(path: string): void;
1627
1628 /** Sends an replaceOne command with this document _id as the query selector. */
1629 replaceOne(replacement: any, callback?: (err: any, raw: any) => void): Query<any>;
1630
1631 /** Sends an update command with this document _id as the query selector. */
1632 update(doc: any, callback?: (err: any, raw: any) => void): Query<any>;
1633 update(doc: any, options: ModelUpdateOptions,
1634 callback?: (err: any, raw: any) => void): Query<any>;
1635
1636 /** Sends an updateOne command with this document _id as the query selector. */
1637 updateOne(doc: any, callback?: (err: any, raw: any) => void): Query<any>;
1638 updateOne(doc: any, options: ModelUpdateOptions,
1639 callback?: (err: any, raw: any) => void): Query<any>;
1640
1641 /**
1642 * Executes registered validation rules for this document.
1643 * @param optional options internal options
1644 * @param callback callback called after validation completes, passing an error if one occurred
1645 */
1646 validate(callback?: (err: any) => void): Promise<void>;
1647 validate(optional: any, callback?: (err: any) => void): Promise<void>;
1648
1649 /**
1650 * Executes registered validation rules (skipping asynchronous validators) for this document.
1651 * This method is useful if you need synchronous validation.
1652 * @param pathsToValidate only validate the given paths
1653 * @returns ValidationError if there are errors during validation, or undefined if there is no error.
1654 */
1655 validateSync(pathsToValidate?: string | string[]): Error.ValidationError | undefined;
1656
1657 /** Hash containing current validation errors. */
1658 errors: any;
1659 /** This documents _id. */
1660 _id: any;
1661 /** Boolean flag specifying if the document is new. */
1662 isNew: boolean;
1663 /** The documents schema. */
1664 schema: Schema;
1665 /** Empty object that you can use for storing properties on the document */
1666 $locals: { [k: string]: any };
1667 }
1668
1669 interface MongooseDocumentOptionals {
1670 /**
1671 * Virtual getter that by default returns the document's _id field cast to a string,
1672 * or in the case of ObjectIds, its hexString. This id getter may be disabled by
1673 * passing the option { id: false } at schema construction time. If disabled, id
1674 * behaves like any other field on a document and can be assigned any value.
1675 */
1676 id?: any;
1677 }
1678
1679 interface DocumentToObjectOptions {
1680 /** apply all getters (path and virtual getters) */
1681 getters?: boolean;
1682 /** apply virtual getters (can override getters option) */
1683 virtuals?: boolean;
1684 /** remove empty objects (defaults to true) */
1685 minimize?: boolean;
1686 /**
1687 * A transform function to apply to the resulting document before returning
1688 * @param doc The mongoose document which is being converted
1689 * @param ret The plain object representation which has been converted
1690 * @param options The options in use (either schema options or the options passed inline)
1691 */
1692 transform?: (doc: any, ret: any, options: any) => any;
1693 /** depopulate any populated paths, replacing them with their original refs (defaults to false) */
1694 depopulate?: boolean;
1695 /** whether to include the version key (defaults to true) */
1696 versionKey?: boolean;
1697 /** whether to convert Maps to POJOs. (defaults to false) */
1698 flattenMaps?: boolean;
1699 }
1700
1701 namespace Types {
1702 /*
1703 * section types/subdocument.js
1704 * http://mongoosejs.com/docs/api.html#types-subdocument-js
1705 */
1706 class Subdocument extends MongooseDocument {
1707 /** Returns the top level document of this sub-document. */
1708 ownerDocument(): MongooseDocument;
1709
1710 /**
1711 * Null-out this subdoc
1712 * @param callback optional callback for compatibility with Document.prototype.remove
1713 */
1714 remove(callback?: (err: any) => void): void;
1715 remove(options: any, callback?: (err: any) => void): void;
1716 }
1717
1718 /*
1719 * section types/array.js
1720 * http://mongoosejs.com/docs/api.html#types-array-js
1721 */
1722 class Array<T> extends global.Array<T> {
1723 /**
1724 * Atomically shifts the array at most one time per document save().
1725 * Calling this mulitple times on an array before saving sends the same command as
1726 * calling it once. This update is implemented using the MongoDB $pop method which
1727 * enforces this restriction.
1728 */
1729 $shift(): T;
1730
1731 /** Alias of pull */
1732 remove(...args: any[]): this;
1733
1734 /**
1735 * Pops the array atomically at most one time per document save().
1736 * Calling this mulitple times on an array before saving sends the same command as
1737 * calling it once. This update is implemented using the MongoDB $pop method which
1738 * enforces this restriction.
1739 */
1740 $pop(): T;
1741
1742 /**
1743 * Adds values to the array if not already present.
1744 * @returns the values that were added
1745 */
1746 addToSet(...args: any[]): T[];
1747
1748 /**
1749 * Return the index of obj or -1 if not found.
1750 * @param obj the item to look for
1751 */
1752 indexOf(obj: any): number;
1753
1754 /** Helper for console.log */
1755 inspect(): any;
1756
1757 /**
1758 * Marks the entire array as modified, which if saved, will store it as a $set
1759 * operation, potentially overwritting any changes that happen between when you
1760 * retrieved the object and when you save it.
1761 * @returns new length of the array
1762 */
1763 nonAtomicPush(...args: any[]): number;
1764
1765 /**
1766 * Wraps Array#pop with proper change tracking.
1767 * marks the entire array as modified which will pass the entire thing to $set
1768 * potentially overwritting any changes that happen between when you retrieved
1769 * the object and when you save it.
1770 */
1771 pop(): T;
1772
1773 /**
1774 * Pulls items from the array atomically. Equality is determined by casting
1775 * the provided value to an embedded document and comparing using
1776 * the Document.equals() function.
1777 */
1778 pull(...args: any[]): this;
1779
1780 /**
1781 * Wraps Array#push with proper change tracking.
1782 * @returns new length of the array
1783 */
1784 push(...args: any[]): number;
1785
1786 /** Sets the casted val at index i and marks the array modified. */
1787 set(i: number, val: any): this;
1788
1789 /**
1790 * Wraps Array#shift with proper change tracking.
1791 * Marks the entire array as modified, which if saved, will store it as a $set operation,
1792 * potentially overwritting any changes that happen between when you retrieved the object
1793 * and when you save it.
1794 */
1795 shift(): T;
1796
1797 /**
1798 * Wraps Array#sort with proper change tracking.
1799 * Marks the entire array as modified, which if saved, will store it as a $set operation,
1800 * potentially overwritting any changes that happen between when you retrieved the object
1801 * and when you save it.
1802 */
1803 // some lib.d.ts have return type "this" and others have return type "T[]"
1804 // which causes errors. Let the inherited array provide the sort() method.
1805 //sort(compareFn?: (a: T, b: T) => number): T[];
1806
1807 /**
1808 * Wraps Array#splice with proper change tracking and casting.
1809 * Marks the entire array as modified, which if saved, will store it as a $set operation,
1810 * potentially overwritting any changes that happen between when you retrieved the object
1811 * and when you save it.
1812 */
1813 splice(...args: any[]): T[];
1814
1815 /** Returns a native js Array. */
1816 toObject(options?: any): T[];
1817
1818 /**
1819 * Wraps Array#unshift with proper change tracking.
1820 * Marks the entire array as modified, which if saved, will store it as a $set operation,
1821 * potentially overwritting any changes that happen between when you retrieved the object
1822 * and when you save it.
1823 */
1824 unshift(...args: any[]): number;
1825 }
1826
1827 /*
1828 * section types/documentarray.js
1829 * http://mongoosejs.com/docs/api.html#types-documentarray-js
1830 */
1831 class DocumentArray<T extends MongooseDocument> extends Types.Array<T> {
1832 /**
1833 * Creates a subdocument casted to this schema.
1834 * This is the same subdocument constructor used for casting.
1835 * @param obj the value to cast to this arrays SubDocument schema
1836 */
1837 create(obj: any): T;
1838
1839 /**
1840 * Searches array items for the first document with a matching _id.
1841 * @returns the subdocument or null if not found.
1842 */
1843 id(id: ObjectId | string | number | NativeBuffer): T;
1844
1845 /** Helper for console.log */
1846 inspect(): T[];
1847
1848 /**
1849 * Returns a native js Array of plain js objects
1850 * @param options optional options to pass to each documents toObject
1851 * method call during conversion
1852 */
1853 toObject(options?: any): T[];
1854 }
1855
1856 /*
1857 * section types/buffer.js
1858 * http://mongoosejs.com/docs/api.html#types-buffer-js
1859 */
1860 class Buffer extends global.Buffer {
1861 /**
1862 * Copies the buffer.
1863 * Buffer#copy does not mark target as modified so you must copy
1864 * from a MongooseBuffer for it to work as expected. This is a
1865 * work around since copy modifies the target, not this.
1866 */
1867 copy(target: NativeBuffer, ...nodeBufferArgs: any[]): number;
1868
1869 /** Determines if this buffer is equals to other buffer */
1870 equals(other: NativeBuffer): boolean;
1871
1872 /** Sets the subtype option and marks the buffer modified. */
1873 subtype(subtype: number): void;
1874
1875 /** Converts this buffer to its Binary type representation. */
1876 toObject(subtype?: number): mongodb.Binary;
1877
1878 /** Writes the buffer. */
1879 write(string: string, ...nodeBufferArgs: any[]): number;
1880 }
1881
1882 /*
1883 * section types/objectid.js
1884 * http://mongoosejs.com/docs/api.html#types-objectid-js
1885 */
1886 var ObjectId: ObjectIdConstructor;
1887
1888 // mongodb.ObjectID does not allow mongoose.Types.ObjectId(id). This is
1889 // commonly used in mongoose and is found in an example in the docs:
1890 // http://mongoosejs.com/docs/api.html#aggregate_Aggregate
1891 // constructor exposes static methods of mongodb.ObjectID and ObjectId(id)
1892 type ObjectIdConstructor = typeof mongodb.ObjectID & {
1893 (s?: string | number): mongodb.ObjectID;
1894 };
1895
1896 // var objectId: mongoose.Types.ObjectId should reference mongodb.ObjectID not
1897 // the ObjectIdConstructor, so we add the interface below
1898 interface ObjectId extends mongodb.ObjectID { }
1899
1900 class Decimal128 extends mongodb.Decimal128 { }
1901
1902 /*
1903 * section types/embedded.js
1904 * http://mongoosejs.com/docs/api.html#types-embedded-js
1905 */
1906 class Embedded extends MongooseDocument {
1907 /** Helper for console.log */
1908 inspect(): any;
1909
1910 /**
1911 * Marks a path as invalid, causing validation to fail.
1912 * @param path the field to invalidate
1913 * @param err error which states the reason path was invalid
1914 */
1915 invalidate(path: string, err: string | NativeError): boolean;
1916
1917 /** Returns the top level document of this sub-document. */
1918 ownerDocument(): MongooseDocument;
1919 /** Returns this sub-documents parent document. */
1920 parent(): MongooseDocument;
1921 /** Returns this sub-documents parent array. */
1922 parentArray(): DocumentArray<MongooseDocument>;
1923
1924 /** Removes the subdocument from its parent array. */
1925 remove(options?: {
1926 noop?: boolean;
1927 }, fn?: (err: any) => void): this;
1928
1929 /**
1930 * Marks the embedded doc modified.
1931 * @param path the path which changed
1932 */
1933 markModified(path: string): void;
1934 }
1935
1936 /**
1937 * section types/map.js
1938 * https://mongoosejs.com/docs/schematypes.html#maps
1939 */
1940 class Map<V> extends global.Map<string, V> {
1941 /** Returns this Map object as a POJO. */
1942 toObject(options: { flattenMaps: true } & object): Record<string, V>;
1943 /** Returns a native js Map. */
1944 toObject(options?: any): GlobalMap<string, V>;
1945 }
1946 }
1947
1948 // Because the mongoose Map type shares a name with the default global interface,
1949 // this type alias has to exist outside of the namespace
1950 interface GlobalMap<K, V> extends Map<K, V> {}
1951
1952 /*
1953 * section query.js
1954 * http://mongoosejs.com/docs/api.html#query-js
1955 *
1956 * Query<T> is for backwards compatibility. Example: Query<T>.find() returns Query<T[]>.
1957 * If later in the query chain a method returns Query<T>, we will need to know type T.
1958 * So we save this type as the second type parameter in DocumentQuery. Since people have
1959 * been using Query<T>, we set it as an alias of DocumentQuery.
1960 *
1961 * Furthermore, Query<T> is used for function that has an option { rawResult: true }.
1962 * for instance findOneAndUpdate.
1963 */
1964 class Query<T> extends DocumentQuery<T, any> { }
1965 class DocumentQuery<T, DocType extends Document, QueryHelpers = {}> extends mquery {
1966 [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
1967
1968 /**
1969 * Specifies a javascript function or expression to pass to MongoDBs query system.
1970 * Only use $where when you have a condition that cannot be met using other MongoDB
1971 * operators like $lt. Be sure to read about all of its caveats before using.
1972 * @param js javascript string or function
1973 */
1974 $where(js: string | Function): this;
1975
1976 /**
1977 * Specifies an $all query condition.
1978 * When called with one argument, the most recent path passed to where() is used.
1979 */
1980 all(val: number): this;
1981 all(path: string, val: number): this;
1982 all(val: any[]): this;
1983 all(path: string, val: any[]): this;
1984
1985 /**
1986 * Specifies arguments for a $and condition.
1987 * @param array array of conditions
1988 */
1989 and(array: any[]): this;
1990
1991 /** Specifies the batchSize option. Cannot be used with distinct() */
1992 batchSize(val: number): this;
1993
1994 /** Get the current error flag value */
1995 error(): Error | null;
1996 /** Unset the error flag set on this query */
1997 error(unset: null): this;
1998 /**
1999 * Set the error flag on this query
2000 * @param err The error flag
2001 */
2002 error(err: Error): this;
2003
2004 /**
2005 * Specifies a $box condition
2006 * @param Upper Right Coords
2007 */
2008 box(val: any): this;
2009 box(lower: number[], upper: number[]): this;
2010
2011 /** Casts this query to the schema of model, If obj is present, it is cast instead of this query.*/
2012 cast(model: any, obj?: any): any;
2013
2014 /**
2015 * Executes the query returning a Promise which will be
2016 * resolved with either the doc(s) or rejected with the error.
2017 * Like .then(), but only takes a rejection handler.
2018 */
2019 catch<TRes>(reject?: (err: any) => void | TRes | PromiseLike<TRes>): Promise<TRes>;
2020
2021 /**
2022 * DEPRECATED Alias for circle
2023 * Specifies a $center or $centerSphere condition.
2024 * @deprecated Use circle instead.
2025 */
2026 center(area: any): this;
2027 center(path: string, area: any): this;
2028 /**
2029 * DEPRECATED Specifies a $centerSphere condition
2030 * @deprecated Use circle instead.
2031 */
2032 centerSphere(path: string, val: any): this;
2033 centerSphere(val: any): this;
2034
2035 /** Specifies a $center or $centerSphere condition. */
2036 circle(area: any): this;
2037 circle(path: string, area: any): this;
2038
2039 /** Adds a collation to this op (MongoDB 3.4 and up) */
2040 collation(value: CollationOptions): this;
2041
2042 /** Specifies the comment option. Cannot be used with distinct() */
2043 comment(val: string): this;
2044
2045 /**
2046 * Specifying this query as a count query. Passing a callback executes the query.
2047 * @param criteria mongodb selector
2048 */
2049 count(callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
2050 count(criteria: FilterQuery<DocType>, callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
2051
2052 /**
2053 * Specifies this query as a `countDocuments()` query. Behaves like `count()`,
2054 * except it always does a full collection scan when passed an empty filter `{}`.
2055 *
2056 * There are also minor differences in how `countDocuments()` handles
2057 * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
2058 * versus `count()`.
2059 *
2060 * Passing a `callback` executes the query.
2061 *
2062 * This function triggers the following middleware.
2063 *
2064 * - `countDocuments()`
2065 *
2066 *
2067 * @param {Object} [criteria] mongodb selector
2068 * @param {Function} [callback] optional params are (error, count)
2069 * @return {Query} this
2070 */
2071 countDocuments(callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
2072 countDocuments(criteria: FilterQuery<DocType>, callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
2073
2074 /**
2075 * Estimates the number of documents in the MongoDB collection. Faster than
2076 * using `countDocuments()` for large collections because
2077 * `estimatedDocumentCount()` uses collection metadata rather than scanning
2078 * the entire collection.
2079 *
2080 * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount)
2081 * @param {Function} [callback] optional params are (error, count)
2082 * @return {Query} this
2083 */
2084 estimatedDocumentCount(callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
2085 estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
2086
2087 /**
2088 * Returns a wrapper around a mongodb driver cursor. A Query<T>Cursor exposes a
2089 * Streams3-compatible interface, as well as a .next() function.
2090 */
2091 cursor(options?: any): QueryCursor<DocType>;
2092
2093 /** Declares or executes a distict() operation. Passing a callback executes the query. */
2094 distinct(callback?: (err: any, res: any[]) => void): Query<any[]> & QueryHelpers;
2095 distinct(field: string, callback?: (err: any, res: any[]) => void): Query<any[]> & QueryHelpers;
2096 distinct(field: string, criteria: any | Query<any>,
2097 callback?: (err: any, res: any[]) => void): Query<any[]> & QueryHelpers;
2098
2099 /** Specifies an $elemMatch condition */
2100 elemMatch(criteria: (elem: Query<any>) => void): this;
2101 elemMatch(criteria: any): this;
2102 elemMatch(path: string | any | Function, criteria: (elem: Query<any>) => void): this;
2103 elemMatch(path: string | any | Function, criteria: any): this;
2104
2105 /** Specifies the complementary comparison value for paths specified with where() */
2106 equals<T>(val: T): this;
2107
2108 /** Executes the query */
2109 exec(callback?: (err: NativeError, res: T) => void): Promise<T>;
2110 exec(operation: string | Function, callback?: (err: any, res: T) => void): Promise<T>;
2111
2112 /** Specifies an $exists condition */
2113 exists(val?: boolean): this;
2114 exists(path: string, val?: boolean): this;
2115
2116 /**
2117 * Finds documents. When no callback is passed, the query is not executed. When the
2118 * query is executed, the result will be an array of documents.
2119 * @param criteria mongodb selector
2120 */
2121 find(callback?: (err: any, res: DocType[]) => void): DocumentQuery<DocType[], DocType, QueryHelpers> & QueryHelpers;
2122 find(criteria: FilterQuery<DocType>,
2123 callback?: (err: any, res: DocType[]) => void): DocumentQuery<DocType[], DocType, QueryHelpers> & QueryHelpers;
2124
2125 /**
2126 * Declares the query a findOne operation. When executed, the first found document is
2127 * passed to the callback. Passing a callback executes the query. The result of the query
2128 * is a single document.
2129 * @param criteria mongodb selector
2130 * @param projection optional fields to return
2131 */
2132 findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2133 findOne(criteria: FilterQuery<DocType>,
2134 callback?: (err: any, res: DocType | null) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2135 findOne(criteria: FilterQuery<DocType>, projection: any,
2136 callback?: (err: any, res: T | null) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2137 findOne(criteria: FilterQuery<DocType>, projection: any, options: { lean: true } & Omit<QueryFindBaseOptions, 'lean'>,
2138 callback?: (err: any, res: T | null) => void): Query<DocumentDefinition<DocType>> & QueryHelpers;
2139 findOne(criteria: FilterQuery<DocType>, projection: any, options: QueryFindBaseOptions,
2140 callback?: (err: any, res: T | null) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2141
2142 /**
2143 * Issues a mongodb findAndModify remove command.
2144 * Finds a matching document, removes it, passing the found document (if any) to the
2145 * callback. Executes immediately if callback is passed.
2146 *
2147 * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify().
2148 * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set
2149 */
2150 findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2151 findOneAndRemove(conditions: FilterQuery<DocType>,
2152 callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2153 findOneAndRemove(conditions: FilterQuery<DocType>, options: { rawResult: true } & QueryFindOneAndRemoveOptions,
2154 callback?: (error: any, doc: mongodb.FindAndModifyWriteOpResultObject<DocType | null>, result: any) => void)
2155 : Query<mongodb.FindAndModifyWriteOpResultObject<DocType | null>> & QueryHelpers;
2156 findOneAndRemove(conditions: FilterQuery<DocType>, options: QueryFindOneAndRemoveOptions,
2157 callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2158
2159 /**
2160 * Issues a mongodb findAndModify update command.
2161 * Finds a matching document, updates it according to the update arg, passing any options, and returns
2162 * the found document (if any) to the callback. The query executes immediately if callback is passed.
2163 *
2164 * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify().
2165 * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set
2166 */
2167 findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2168 findOneAndUpdate(update: UpdateQuery<DocType>,
2169 callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2170 findOneAndUpdate(query: FilterQuery<DocType>, update: UpdateQuery<DocType>,
2171 callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2172 findOneAndUpdate(query: FilterQuery<DocType>, update: UpdateQuery<DocType>,
2173 options: { rawResult: true } & { upsert: true } & { new: true } & QueryFindOneAndUpdateOptions,
2174 callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<DocType>, res: any) => void)
2175 : Query<mongodb.FindAndModifyWriteOpResultObject<DocType>> & QueryHelpers;
2176 findOneAndUpdate(query: FilterQuery<DocType>, update: UpdateQuery<DocType>,
2177 options: { upsert: true } & { new: true } & QueryFindOneAndUpdateOptions,
2178 callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery<DocType, DocType, QueryHelpers> & QueryHelpers;
2179 findOneAndUpdate(query: FilterQuery<DocType>, update: UpdateQuery<DocType>, options: { rawResult: true } & QueryFindOneAndUpdateOptions,
2180 callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<DocType | null>, res: any) => void)
2181 : Query<mongodb.FindAndModifyWriteOpResultObject<DocType | null>> & QueryHelpers;
2182 findOneAndUpdate(query: FilterQuery<DocType>, update: UpdateQuery<DocType>,
2183 options: { lean: true } & Omit<QueryFindOneAndUpdateOptions, 'lean'>,
2184 callback?: (err: any, doc: DocumentDefinition<DocType>, res: any) => void)
2185 : Query<DocumentDefinition<DocType>> & QueryHelpers;
2186 findOneAndUpdate(query: FilterQuery<DocType>, update: UpdateQuery<DocType>, options: QueryFindOneAndUpdateOptions,
2187 callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery<DocType | null, DocType, QueryHelpers> & QueryHelpers;
2188
2189 /**
2190 * Specifies a $geometry condition. geometry() must come after either intersects() or within().
2191 * @param object Must contain a type property which is a String and a coordinates property which
2192 * is an Array. See the examples.
2193 */
2194 geometry(object: { type: string, coordinates: any[] }): this;
2195
2196 /**
2197 * Returns the current query options as a JSON object.
2198 * @returns current query options
2199 */
2200 getOptions(): any;
2201
2202 /**
2203 * Returns the current query conditions as a JSON object.
2204 * @returns current query conditions
2205 * @deprecated You should use getFilter() instead of getQuery() where possible. getQuery() will likely be deprecated in a future release.
2206 */
2207 getQuery(): any;
2208
2209 /**
2210 * Returns the current query filter (also known as conditions) as a POJO.
2211 * @returns current query filter
2212 */
2213 getFilter(): any;
2214
2215 /**
2216 * Returns the current update operations as a JSON object.
2217 * @returns current update operations
2218 */
2219 getUpdate(): any;
2220
2221 /**
2222 * Specifies a $gt query condition.
2223 * When called with one argument, the most recent path passed to where() is used.
2224 */
2225 gt<T>(val: T): this;
2226 gt<T>(path: string, val: T): this;
2227
2228 /**
2229 * Specifies a $gte query condition.
2230 * When called with one argument, the most recent path passed to where() is used.
2231 */
2232 gte<T>(val: T): this;
2233 gte<T>(path: string, val: T): this;
2234
2235 /**
2236 * Sets query hints.
2237 * @param val a hint object
2238 */
2239 hint(val: any): this;
2240
2241 /**
2242 * Specifies an $in query condition.
2243 * When called with one argument, the most recent path passed to where() is used.
2244 */
2245 in(val: any[]): this;
2246 in(path: string, val: any[]): this;
2247
2248 /** Declares an intersects query for geometry(). MUST be used after where(). */
2249 intersects(arg?: any): this;
2250
2251 /**
2252 * Sets the lean option.
2253 * Documents returned from queries with the lean option enabled are plain
2254 * javascript objects, not MongooseDocuments. They have no save method,
2255 * getters/setters or other Mongoose magic applied.
2256 * @param {Boolean|Object} bool defaults to true
2257 */
2258 lean<P = DocumentDefinition<DocType>>(bool?: boolean | object): Query<T extends Array<any> ? P[] : (P | null)> & QueryHelpers;
2259
2260 /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */
2261 limit(val: number): this;
2262
2263 /**
2264 * Specifies a $lt query condition.
2265 * When called with one argument, the most recent path passed to where() is used.
2266 */
2267 lt<T>(val: T): this;
2268 lt<T>(path: string, val: T): this;
2269
2270 /**
2271 * Specifies a $lte query condition.
2272 * When called with one argument, the most recent path passed to where() is used.
2273 */
2274 lte<T>(val: T): this;
2275 lte<T>(path: string, val: T): this;
2276
2277 /**
2278 * Runs a function fn and treats the return value of fn as the new value for the query to resolve to.
2279 * Any functions you pass to map() will run after any post hooks.
2280 */
2281 map<TRes>(fn: (res: T) => TRes): DocumentQuery<TRes, DocType, QueryHelpers> & QueryHelpers;
2282
2283 /**
2284 * Specifies a $maxDistance query condition.
2285 * When called with one argument, the most recent path passed to where() is used.
2286 */
2287 maxDistance(val: number): this;
2288 maxDistance(path: string, val: number): this;
2289
2290 /** @deprecated Alias of maxScan */
2291 maxscan(val: number): this;
2292 /** Specifies the maxScan option. Cannot be used with distinct() */
2293 maxScan(val: number): this;
2294
2295 /** Specifies the maxTimeMS options. */
2296 maxTimeMS(val: number): this;
2297
2298 /**
2299 * Merges another Query or conditions object into this one.
2300 * When a Query is passed, conditions, field selection and options are merged.
2301 */
2302 merge(source: any | Query<any>): this;
2303
2304 /** Specifies a $mod condition */
2305 mod(val: number[]): this;
2306 mod(path: string, val: number[]): this;
2307
2308 /**
2309 * Specifies a $ne query condition.
2310 * When called with one argument, the most recent path passed to where() is used.
2311 */
2312 ne(val: any): this;
2313 ne(path: string, val: any): this;
2314
2315 /** Specifies a $near or $nearSphere condition. */
2316 near(val: any): this;
2317 near(path: string, val: any): this;
2318
2319 /**
2320 * DEPRECATED Specifies a $nearSphere condition
2321 * @deprecated Use query.near() instead with the spherical option set to true.
2322 */
2323 nearSphere(val: any): this;
2324 nearSphere(path: string, val: any): this;
2325
2326 /**
2327 * Specifies a $nin query condition.
2328 * When called with one argument, the most recent path passed to where() is used.
2329 */
2330 nin(val: any[]): this;
2331 nin(path: string, val: any[]): this;
2332
2333 /**
2334 * Specifies arguments for a $nor condition.
2335 * @param array array of conditions
2336 */
2337 nor(array: any[]): this;
2338
2339 /**
2340 * Specifies arguments for an $or condition.
2341 * @param array array of conditions
2342 */
2343 or(array: any[]): this;
2344
2345 /**
2346 * Make this query throw an error if no documents match the given `filter`.
2347 * This is handy for integrating with async/await, because `orFail()` saves you
2348 * an extra `if` statement to check if no document was found.
2349 *
2350 * Example:
2351 *
2352 * // Throws if no doc returned
2353 * await Model.findOne({ foo: 'bar' }).orFail();
2354 *
2355 * // Throws if no document was updated
2356 * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
2357 *
2358 * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
2359 * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
2360 *
2361 * // Throws "Not found" error if no document was found
2362 * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
2363 * orFail(() => Error('Not found'));
2364 *
2365 * @param err optional error to throw if no docs match `filter`
2366 */
2367 orFail(err?: Error | (() => Error)): DocumentQuery<NonNullable<T>, DocType, QueryHelpers>;
2368
2369 /** Specifies a $polygon condition */
2370 polygon(...coordinatePairs: number[][]): this;
2371 polygon(path: string, ...coordinatePairs: number[][]): this;
2372
2373 /**
2374 * Specifies paths which should be populated with other documents.
2375 * Paths are populated after the query executes and a response is received. A separate
2376 * query is then executed for each path specified for population. After a response for
2377 * each query has also been returned, the results are passed to the callback.
2378 * @param path either the path to populate or an object specifying all parameters
2379 * @param select Field selection for the population query
2380 * @param model The model you wish to use for population. If not specified, populate
2381 * will look up the model by the name in the Schema's ref field.
2382 * @param match Conditions for the population query
2383 * @param options Options for the population query (sort, etc)
2384 */
2385 populate(path: string | any, select?: string | any, model?: any,
2386 match?: any, options?: any): this;
2387 populate(options: QueryPopulateOptions | QueryPopulateOptions[]): this;
2388
2389 /**
2390 * Determines the MongoDB nodes from which to read.
2391 * @param pref one of the listed preference options or aliases
2392 * @param tags optional tags for this query
2393 */
2394 read(pref: string, tags?: any[]): this;
2395
2396 /**
2397 * Sets the readConcern option for the query.
2398 * @param level one of the listed read concern level or their aliases
2399 */
2400 readConcern(level: string): this;
2401
2402 /**
2403 * Specifies a $regex query condition.
2404 * When called with one argument, the most recent path passed to where() is used.
2405 */
2406 regex(val: RegExp): this;
2407 regex(path: string, val: RegExp): this;
2408
2409 /**
2410 * Declare and/or execute this query as a remove() operation.
2411 * The operation is only executed when a callback is passed. To force execution without a callback,
2412 * you must first call remove() and then execute it by using the exec() method.
2413 * @param criteria mongodb selector
2414 */
2415 remove(callback?: (err: any) => void): Query<mongodb.WriteOpResult['result']> & QueryHelpers;
2416 remove(criteria: FilterQuery<DocType> | Query<any>, callback?: (err: any) => void): Query<mongodb.WriteOpResult['result']> & QueryHelpers;
2417
2418 /** Specifies which document fields to include or exclude (also known as the query "projection") */
2419 select(arg: string | any): this;
2420 /** Determines if field selection has been made. */
2421 selected(): boolean;
2422 /** Determines if exclusive field selection has been made.*/
2423 selectedExclusively(): boolean;
2424 /** Determines if inclusive field selection has been made. */
2425 selectedInclusively(): boolean;
2426 /** Sets query options. */
2427 setOptions(options: any): this;
2428 /** Sets query conditions to the provided JSON object. */
2429 setQuery(conditions: any): this;
2430
2431 /**
2432 * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/)
2433 * associated with this query. Sessions are how you mark a query as part of a
2434 * [transaction](/docs/transactions.html).
2435 */
2436 session(session: mongodb.ClientSession | null): this;
2437
2438 /**
2439 * Specifies a $size query condition.
2440 * When called with one argument, the most recent path passed to where() is used.
2441 */
2442 size(val: number): this;
2443 size(path: string, val: number): this;
2444
2445 /** Specifies the number of documents to skip. Cannot be used with distinct() */
2446 skip(val: number): this;
2447
2448 /**
2449 * DEPRECATED Sets the slaveOk option.
2450 * @param v defaults to true
2451 * @deprecated in MongoDB 2.2 in favor of read preferences.
2452 */
2453 slaveOk(v?: boolean): this;
2454
2455 /**
2456 * Specifies a $slice projection for an array.
2457 * @param val number/range of elements to slice
2458 */
2459 slice(val: number | number[]): this;
2460 slice(path: string, val: number | number[]): this;
2461
2462 /** Specifies this query as a snapshot query. Cannot be used with distinct() */
2463 snapshot(v?: boolean): this;
2464
2465 /**
2466 * Sets the sort order
2467 * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.
2468 * If a string is passed, it must be a space delimited list of path names. The
2469 * sort order of each path is ascending unless the path name is prefixed with -
2470 * which will be treated as descending.
2471 */
2472 sort(arg: string | any): this;
2473
2474 /**
2475 * Sets the tailable option (for use with capped collections). Cannot be used with distinct()
2476 * @param bool defaults to true
2477 * @param opts options to set
2478 * @param opts.numberOfRetries if cursor is exhausted, retry this many times before giving up
2479 * @param opts.tailableRetryInterval if cursor is exhausted, wait this many milliseconds before retrying
2480 */
2481 tailable(bool?: boolean, opts?: {
2482 numberOfRetries?: number;
2483 tailableRetryInterval?: number;
2484 }): this;
2485
2486 /** Executes this query and returns a promise */
2487 then: Promise<T>["then"];
2488
2489 /**
2490 * Converts this query to a customized, reusable query
2491 * constructor with all arguments and options retained.
2492 */
2493 toConstructor<T>(): new (...args: any[]) => Query<T> & QueryHelpers;
2494 toConstructor<T, Doc extends Document>(): new (...args: any[]) => DocumentQuery<T, Doc, QueryHelpers> & QueryHelpers;
2495
2496 /**
2497 * Declare and/or execute this query as an update() operation.
2498 * All paths passed that are not $atomic operations will become $set ops.
2499 * @param doc the update command
2500 */
2501 update(callback?: (err: any, affectedRows: number) => void): Query<number> & QueryHelpers;
2502 update(doc: UpdateQuery<DocType>, callback?: (err: any, affectedRows: number) => void): Query<number> & QueryHelpers;
2503 update(criteria: FilterQuery<DocType>, doc: UpdateQuery<DocType>,
2504 callback?: (err: any, affectedRows: number) => void): Query<number> & QueryHelpers;
2505 update(criteria: FilterQuery<DocType>, doc: UpdateQuery<DocType>, options: QueryUpdateOptions,
2506 callback?: (err: any, affectedRows: number) => void): Query<number> & QueryHelpers;
2507
2508 /** Specifies a path for use with chaining. */
2509 where(path?: string | any, val?: any): this;
2510
2511 /** Defines a $within or $geoWithin argument for geo-spatial queries. */
2512 within(val?: any): this;
2513 within(coordinate: number[], ...coordinatePairs: number[][]): this;
2514
2515 wtimeout(ms?: number): this;
2516
2517 /** Flag to opt out of using $geoWithin. */
2518 static use$geoWithin: boolean;
2519 }
2520
2521 // https://github.com/aheckmann/mquery
2522 // mquery currently does not have a type definition please
2523 // replace it if one is ever created
2524 class mquery { }
2525
2526 // https://mongoosejs.com/docs/api.html#query_Query-setOptions
2527 interface QueryFindBaseOptions {
2528 /** Sets a default collation for every query and aggregation. */
2529 collation?: CollationOptions;
2530 explain?: any;
2531 lean?: boolean;
2532 populate?: string | ModelPopulateOptions;
2533 /** like select, it determines which fields to return */
2534 projection?: any;
2535 /** use client session for transaction */
2536 session?: ClientSession;
2537 }
2538
2539 interface QueryFindOptions extends QueryFindBaseOptions {
2540 batchSize?: number;
2541 comment?: any;
2542 hint?: any;
2543 limit?: number;
2544 maxscan?: number;
2545 readPreference?: mongodb.ReadPreferenceMode;
2546 skip?: number;
2547 snapshot?: any;
2548 sort?: any;
2549 tailable?: any;
2550 }
2551
2552 interface QueryFindOneAndRemoveOptions {
2553 /**
2554 * if multiple docs are found by the conditions, sets the sort order to choose
2555 * which doc to update
2556 */
2557 sort?: any;
2558 /** puts a time limit on the query - requires mongodb >= 2.6.0 */
2559 maxTimeMS?: number;
2560 /** sets the document fields to return */
2561 select?: any;
2562 /** like select, it determines which fields to return */
2563 projection?: any;
2564 /** if true, returns the raw result from the MongoDB driver */
2565 rawResult?: boolean;
2566 /** overwrites the schema's strict mode option for this update */
2567 strict?: boolean | "throw";
2568 /** use client session for transaction */
2569 session?: ClientSession;
2570 }
2571
2572 interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions {
2573 /** if true, return the modified document rather than the original. defaults to false (changed in 4.0) */
2574 new?: boolean;
2575 /** creates the object if it doesn't exist. defaults to false. */
2576 upsert?: boolean;
2577 /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */
2578 runValidators?: boolean;
2579 /**
2580 * if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document
2581 * is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator.
2582 */
2583 setDefaultsOnInsert?: boolean;
2584 /**
2585 * if set to 'query' and runValidators is on, this will refer to the query in custom validator
2586 * functions that update validation runs. Does nothing if runValidators is false.
2587 */
2588 context?: string;
2589 /**
2590 * by default, mongoose only returns the first error that occurred in casting the query.
2591 * Turn on this option to aggregate all the cast errors.
2592 */
2593 multipleCastError?: boolean;
2594 /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */
2595 fields?: any | string;
2596 /**
2597 * Only update elements that match the arrayFilters conditions in the document or documents that match the query conditions.
2598 */
2599 arrayFilters?: { [key: string]: any }[];
2600 /**
2601 * if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean() and the Mongoose lean tutorial.
2602 */
2603 lean?: any;
2604 /** If true, delete any properties whose value is undefined when casting an update. In other words,
2605 if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined })
2606 before sending the update to the server.**/
2607 omitUndefined?: boolean;
2608 /**
2609 * If set to false and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps.
2610 * Does nothing if schema-level timestamps are not set.
2611 */
2612 timestamps?:boolean;
2613 /**
2614 * True by default. Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().
2615 */
2616 useFindAndModify?:boolean;
2617 /**
2618 * False by default. Setting this to true allows the update to overwrite the existing document if no update
2619 * operators are included in the update. When set to false, mongoose will wrap the update in a $set.
2620 */
2621 overwrite?: boolean;
2622 }
2623
2624 interface QueryUpdateOptions extends ModelUpdateOptions {
2625 /**
2626 * if set to 'query' and runValidators is on, this will refer to the query
2627 * in customvalidator functions that update validation runs. Does nothing
2628 * if runValidators is false.
2629 */
2630 context?: string;
2631 }
2632
2633 interface CollationOptions {
2634 locale?: string;
2635 caseLevel?: boolean;
2636 caseFirst?: string;
2637 strength?: number;
2638 numericOrdering?: boolean;
2639 alternate?: string;
2640 maxVariable?: string;
2641 backwards?: boolean;
2642 }
2643
2644 namespace Schema {
2645 namespace Types {
2646 /*
2647 * section schema/array.js
2648 * http://mongoosejs.com/docs/api.html#schema-array-js
2649 */
2650 class Array extends SchemaType {
2651 /** Array SchemaType constructor */
2652 constructor(key: string, cast?: SchemaType, options?: any);
2653
2654 /**
2655 * Check if the given value satisfies a required validator. The given value
2656 * must be not null nor undefined, and have a non-zero length.
2657 */
2658 checkRequired<T extends { length: number }>(value: T): boolean;
2659
2660 /** This schema type's name, to defend against minifiers that mangle function names. */
2661 static schemaName: string;
2662 }
2663
2664 /*
2665 * section schema/string.js
2666 * http://mongoosejs.com/docs/api.html#schema-string-js
2667 */
2668 class String extends SchemaType {
2669 /** String SchemaType constructor. */
2670 constructor(key: string, options?: any);
2671
2672 /** Check if the given value satisfies a required validator. */
2673 checkRequired(value: any, doc: MongooseDocument): boolean;
2674
2675 /**
2676 * Adds an enum validator
2677 * @param args enumeration values
2678 */
2679 enum(args: string | string[] | any): this;
2680
2681 /** Adds a lowercase setter. */
2682 lowercase(): this;
2683
2684 /**
2685 * Sets a regexp validator. Any value that does not pass regExp.test(val) will fail validation.
2686 * @param regExp regular expression to test against
2687 * @param message optional custom error message
2688 */
2689 match(regExp: RegExp, message?: string): this;
2690
2691 /**
2692 * Sets a maximum length validator.
2693 * @param value maximum string length
2694 * @param message optional custom error message
2695 */
2696 maxlength(value: number, message?: string): this;
2697
2698 /**
2699 * Sets a minimum length validator.
2700 * @param value minimum string length
2701 * @param message optional custom error message
2702 */
2703 minlength(value: number, message?: string): this;
2704
2705 /** Adds a trim setter. The string value will be trimmed when set. */
2706 trim(): this;
2707 /** Adds an uppercase setter. */
2708 uppercase(): this;
2709
2710 /** This schema type's name, to defend against minifiers that mangle function names. */
2711 static schemaName: string;
2712
2713 }
2714
2715 /*
2716 * section schema/documentarray.js
2717 * http://mongoosejs.com/docs/api.html#schema-documentarray-js
2718 */
2719 class DocumentArray extends Array {
2720 /** SubdocsArray SchemaType constructor */
2721 constructor(key: string, schema: Schema, options?: any);
2722
2723 /** This schema type's name, to defend against minifiers that mangle function names. */
2724 static schemaName: string;
2725
2726 /**
2727 * Adds a discriminator type.
2728 * @param name discriminator model name
2729 * @param schema discriminator model schema
2730 * @param value the string stored in the `discriminatorKey` property
2731 */
2732 discriminator<U extends Document>(name: string, schema: Schema, value?: string): Model<U>;
2733
2734 /**
2735 * Adds a discriminator type.
2736 * @param name discriminator model name
2737 * @param schema discriminator model schema
2738 * @param value the string stored in the `discriminatorKey` property
2739 */
2740 discriminator<U extends Document, M extends Model<U>>(name: string, schema: Schema, value?: string): M;
2741
2742 }
2743
2744 /*
2745 * section schema/number.js
2746 * http://mongoosejs.com/docs/api.html#schema-number-js
2747 */
2748 class Number extends SchemaType {
2749 /** Number SchemaType constructor. */
2750 constructor(key: string, options?: any);
2751
2752 /** Check if the given value satisfies a required validator. */
2753 checkRequired(value: any, doc: MongooseDocument): boolean;
2754
2755 /**
2756 * Sets a maximum number validator.
2757 * @param maximum number
2758 * @param message optional custom error message
2759 */
2760 max(maximum: number, message?: string): this;
2761
2762 /**
2763 * Sets a minimum number validator.
2764 * @param value minimum number
2765 * @param message optional custom error message
2766 */
2767 min(value: number, message?: string): this;
2768
2769 /** This schema type's name, to defend against minifiers that mangle function names. */
2770 static schemaName: string;
2771 }
2772
2773 /*
2774 * section schema/date.js
2775 * http://mongoosejs.com/docs/api.html#schema-date-js
2776 */
2777 class Date extends SchemaType {
2778 /** Date SchemaType constructor. */
2779 constructor(key: string, options?: any);
2780
2781 /**
2782 * Check if the given value satisfies a required validator. To satisfy
2783 * a required validator, the given value must be an instance of Date.
2784 */
2785 checkRequired(value: any, doc: MongooseDocument): boolean;
2786
2787 /** Declares a TTL index (rounded to the nearest second) for Date types only. */
2788 expires(when: number | string): this;
2789
2790 /**
2791 * Sets a maximum date validator.
2792 * @param maximum date
2793 * @param message optional custom error message
2794 */
2795 max(maximum: NativeDate, message?: string): this;
2796
2797 /**
2798 * Sets a minimum date validator.
2799 * @param value minimum date
2800 * @param message optional custom error message
2801 */
2802 min(value: NativeDate, message?: string): this;
2803
2804 /** This schema type's name, to defend against minifiers that mangle function names. */
2805 static schemaName: string;
2806 }
2807
2808 /*
2809 * section schema/buffer.js
2810 * http://mongoosejs.com/docs/api.html#schema-buffer-js
2811 */
2812 class Buffer extends SchemaType {
2813 /** Buffer SchemaType constructor */
2814 constructor(key: string, options?: any);
2815
2816 /**
2817 * Check if the given value satisfies a required validator. To satisfy a
2818 * required validator, a buffer must not be null or undefined and have
2819 * non-zero length.
2820 */
2821 checkRequired(value: any, doc: MongooseDocument): boolean;
2822
2823 /** This schema type's name, to defend against minifiers that mangle function names. */
2824 static schemaName: string;
2825
2826 }
2827
2828 /*
2829 * section schema/boolean.js
2830 * http://mongoosejs.com/docs/api.html#schema-boolean-js
2831 */
2832 class Boolean extends SchemaType {
2833 /** Boolean SchemaType constructor. */
2834 constructor(path: string, options?: any);
2835
2836 /**
2837 * Check if the given value satisfies a required validator. For a
2838 * boolean to satisfy a required validator, it must be strictly
2839 * equal to true or to false.
2840 */
2841 checkRequired(value: any): boolean;
2842
2843 /** This schema type's name, to defend against minifiers that mangle function names. */
2844 static schemaName: string;
2845 }
2846
2847 /*
2848 * section schema/objectid.js
2849 * http://mongoosejs.com/docs/api.html#schema-objectid-js
2850 */
2851 class ObjectId extends SchemaType {
2852 /** ObjectId SchemaType constructor. */
2853 constructor(key: string, options?: any);
2854
2855 /**
2856 * Adds an auto-generated ObjectId default if turnOn is true.
2857 * @param turnOn auto generated ObjectId defaults
2858 */
2859 auto(turnOn: boolean): this;
2860
2861 /** Check if the given value satisfies a required validator. */
2862 checkRequired(value: any, doc: MongooseDocument): boolean;
2863
2864 /** This schema type's name, to defend against minifiers that mangle function names. */
2865 static schemaName: string;
2866 }
2867 /*
2868 * section schema/decimal128.js
2869 * http://mongoosejs.com/docs/api.html#schema-decimal128-js
2870 */
2871 class Decimal128 extends SchemaType {
2872 /** Decimal128 SchemaType constructor. */
2873 constructor(key: string, options?: any);
2874
2875 /** Check if the given value satisfies a required validator. */
2876 checkRequired(value: any, doc: MongooseDocument): boolean;
2877
2878 /** This schema type's name, to defend against minifiers that mangle function names. */
2879 static schemaName: string;
2880 }
2881
2882 /*
2883 * section schema/mixed.js
2884 * http://mongoosejs.com/docs/api.html#schema-mixed-js
2885 */
2886 class Mixed extends SchemaType {
2887 /** Mixed SchemaType constructor. */
2888 constructor(path: string, options?: any);
2889
2890 /** This schema type's name, to defend against minifiers that mangle function names. */
2891 static schemaName: string;
2892 }
2893
2894 /*
2895 * section schema/embedded.js
2896 * http://mongoosejs.com/docs/api.html#schema-embedded-js
2897 */
2898 class Embedded extends SchemaType {
2899 /** Sub-schema schematype constructor */
2900 constructor(schema: Schema, key: string, options?: any);
2901 }
2902
2903 /**
2904 * section schema/map.js
2905 * https://mongoosejs.com/docs/schematypes.html#maps
2906 */
2907 class Map extends SchemaType {
2908 /** Sub-schema schematype constructor */
2909 constructor(key: string, options?: any);
2910 }
2911 }
2912 }
2913
2914 /*
2915 * section aggregate.js
2916 * http://mongoosejs.com/docs/api.html#aggregate-js
2917 */
2918 class Aggregate<T> {
2919 /**
2920 * Aggregate constructor used for building aggregation pipelines.
2921 * Returned when calling Model.aggregate().
2922 * @param ops aggregation operator(s) or operator array
2923 */
2924 constructor(ops?: any | any[], ...args: any[]);
2925
2926 /** Adds a cursor flag */
2927 addCursorFlag(flag: string, value: boolean): this;
2928
2929 /**
2930 * Appends a new $addFields operator to this aggregate pipeline. Requires MongoDB v3.4+ to work
2931 * @param arg field specification
2932 */
2933 addFields(arg: any): this;
2934
2935 /**
2936 * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)
2937 * @param value Should tell server it can use hard drive to store data during aggregation.
2938 * @param tags optional tags for this query
2939 */
2940 allowDiskUse(value: boolean, tags?: any[]): this;
2941
2942 /**
2943 * Appends new operators to this aggregate pipeline
2944 * @param ops operator(s) to append
2945 */
2946 append(...ops: any[]): this;
2947
2948 /** Adds a collation. */
2949 collation(options: CollationOptions): this;
2950
2951 /**
2952 * Appends a new $count operator to this aggregate pipeline.
2953 * @param countName name of the count field
2954 */
2955 count(countName: string): this;
2956
2957 /**
2958 * Sets the cursor option option for the aggregation query (ignored for < 2.6.0).
2959 * Note the different syntax below: .exec() returns a cursor object, and no callback
2960 * is necessary.
2961 * @param options set the cursor batch size
2962 */
2963 cursor(options: any): this;
2964
2965 /**
2966 * Appends a new $facet operator to this aggregate pipeline.
2967 * @param arg $facet operator contents
2968 */
2969 facet(arg: { [outputField: string]: object[] }): this;
2970
2971 // If cursor option is on, could return an object
2972 /** Executes the aggregate pipeline on the currently bound Model. */
2973 exec(callback?: (err: any, result: T) => void): Promise<T> | any;
2974
2975 /** Execute the aggregation with explain */
2976 explain(callback?: (err: any, result: T) => void): Promise<T>;
2977
2978 /**
2979 * Appends a new custom $group operator to this aggregate pipeline.
2980 * @param arg $group operator contents
2981 */
2982 group(arg: any): this;
2983
2984 /**
2985 * Sets the hint option for the aggregation query (ignored for < 3.6.0)
2986 * @param value a hint object or the index name
2987 */
2988 hint(value: object | string): this;
2989
2990 /**
2991 * Appends a new $limit operator to this aggregate pipeline.
2992 * @param num maximum number of records to pass to the next stage
2993 */
2994 limit(num: number): this;
2995
2996 /**
2997 * Appends new custom $lookup operator(s) to this aggregate pipeline.
2998 * @param options to $lookup as described in the above link
2999 */
3000 lookup(options: any): this;
3001
3002 /**
3003 * Appends a new custom $match operator to this aggregate pipeline.
3004 * @param arg $match operator contents
3005 */
3006 match(arg: any): this;
3007
3008 /**
3009 * Binds this aggregate to a model.
3010 * @param model the model to which the aggregate is to be bound
3011 */
3012 model(model: any): this;
3013
3014 /**
3015 * Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection.
3016 * Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if { allowDiskUse: true } is specified.
3017 * @param options options to $graphLookup
3018 */
3019 graphLookup(options: any): this;
3020
3021 /**
3022 * Appends a new $geoNear operator to this aggregate pipeline.
3023 * MUST be used as the first operator in the pipeline.
3024 */
3025 near(parameters: any): this;
3026
3027 /**
3028 * Lets you set arbitrary options, for middleware or plugins.
3029 * @param value keys to merge into current options
3030 */
3031 option(value: any): this;
3032
3033 /** Returns the current pipeline */
3034 pipeline(): any[];
3035
3036 /**
3037 * Appends a new $project operator to this aggregate pipeline.
3038 * Mongoose query selection syntax is also supported.
3039 * @param arg field specification
3040 */
3041 project(arg: string | any): this;
3042
3043 /**
3044 * Sets the readPreference option for the aggregation query.
3045 * @param pref one of the listed preference options or their aliases
3046 * @param tags optional tags for this query
3047 */
3048 read(pref: string, tags?: any[]): this;
3049
3050 /**
3051 * Appends a new $replaceRoot operator to this aggregate pipeline.
3052 * Note that the $replaceRoot operator requires field strings to start with '$'. If you are passing in a string Mongoose will prepend '$' if the specified field doesn't start '$'. If you are passing in an object the strings in your expression will not be altered.
3053 * @param newRoot field or document which will become the new root document
3054 */
3055 replaceRoot(newRoot: string | object): this;
3056
3057 /**
3058 * Appends new custom $sample operator(s) to this aggregate pipeline.
3059 * @param size number of random documents to pick
3060 */
3061 sample(size: number): this;
3062
3063 session(session: mongodb.ClientSession | null): this;
3064 /**
3065 * Appends a new $skip operator to this aggregate pipeline.
3066 * @param num number of records to skip before next stage
3067 */
3068 skip(num: number): this;
3069
3070 /**
3071 * Appends a new $sort operator to this aggregate pipeline.
3072 * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.
3073 * If a string is passed, it must be a space delimited list of path names. The sort order
3074 * of each path is ascending unless the path name is prefixed with - which will be treated
3075 * as descending.
3076 */
3077 sort(arg: string | any): this;
3078
3079 /** Provides promise for aggregate. */
3080 then: Promise<T>["then"];
3081
3082 /**
3083 * Appends new custom $unwind operator(s) to this aggregate pipeline.
3084 * Note that the $unwind operator requires the path name to start with '$'.
3085 * Mongoose will prepend '$' if the specified field doesn't start '$'.
3086 * @param fields the field(s) to unwind
3087 */
3088 unwind(...fields: string[]): this;
3089 /**
3090 * Appends new custom $unwind operator(s) to this aggregate pipeline
3091 * new in mongodb 3.2
3092 */
3093 unwind(...opts: { path: string, includeArrayIndex?: string, preserveNullAndEmptyArrays?: boolean }[]): this;
3094 }
3095
3096 /*
3097 * section schematype.js
3098 * http://mongoosejs.com/docs/api.html#schematype-js
3099 */
3100 class SchemaType {
3101 /** SchemaType constructor */
3102 constructor(path: string, options?: any, instance?: string);
3103
3104 /**
3105 * Sets a default value for this SchemaType.
3106 * Defaults can be either functions which return the value to use as the
3107 * default or the literal value itself. Either way, the value will be cast
3108 * based on its schema type before being set during document creation.
3109 * @param val the default value
3110 */
3111 default(val: any): any;
3112
3113 /** Adds a getter to this schematype. */
3114 get(fn: Function): this;
3115
3116 /**
3117 * Declares the index options for this schematype.
3118 * Indexes are created in the background by default. Specify background: false to override.
3119 */
3120 index(options: any | boolean | string): this;
3121
3122 /**
3123 * Adds a required validator to this SchemaType. The validator gets added
3124 * to the front of this SchemaType's validators array using unshift().
3125 * @param required enable/disable the validator
3126 * @param message optional custom error message
3127 */
3128 required(required: boolean, message?: string): this;
3129
3130 /** Sets default select() behavior for this path. */
3131 select(val: boolean): this;
3132 /** Adds a setter to this schematype. */
3133 set(fn: Function): this;
3134 /** Declares a sparse index. */
3135 sparse(bool: boolean): this;
3136 /** Declares a full text index. */
3137 text(bool: boolean): this;
3138 /** Declares an unique index. */
3139 unique(bool: boolean): this;
3140
3141 /**
3142 * Adds validator(s) for this document path.
3143 * Validators always receive the value to validate as their first argument
3144 * and must return Boolean. Returning false means validation failed.
3145 * @param obj validator
3146 * @param errorMsg optional error message
3147 * @param type optional validator type
3148 */
3149 validate(obj: RegExp | Function | any, errorMsg?: string,
3150 type?: string): this;
3151 }
3152
3153 /*
3154 * section promise.js
3155 * http://mongoosejs.com/docs/api.html#promise-js
3156 */
3157 /**
3158 * To assign your own promise library:
3159 *
3160 * 1. Typescript does not allow assigning properties of imported modules.
3161 * To avoid compile errors use one of the options below in your code:
3162 *
3163 * - (<any>mongoose).Promise = YOUR_PROMISE;
3164 * - require('mongoose').Promise = YOUR_PROMISE;
3165 * - import mongoose = require('mongoose');
3166 * mongoose.Promise = YOUR_PROMISE;
3167 *
3168 * 2. To assign type definitions for your promise library, you will need
3169 * to have a .d.ts file with the following code when you compile:
3170 *
3171 * - import * as Q from 'q';
3172 * declare module 'mongoose' {
3173 * type Promise<T> = Q.promise<T>;
3174 * }
3175 *
3176 * - import * as Bluebird from 'bluebird';
3177 * declare module 'mongoose' {
3178 * type Promise<T> = Bluebird<T>;
3179 * }
3180 *
3181 * Uses global.Promise by default. If you would like to use mongoose default
3182 * mpromise implementation (which is deprecated), you can omit step 1 and
3183 * run npm install @types/mongoose-promise
3184 */
3185 export var Promise: any;
3186 export var PromiseProvider: any;
3187
3188 /*
3189 * section model.js
3190 * http://mongoosejs.com/docs/api.html#model-js
3191 */
3192 export var Model: Model<any>;
3193 interface Model<T extends Document, QueryHelpers = {}> extends NodeJS.EventEmitter, ModelProperties {
3194 /** Base Mongoose instance the model uses. */
3195 base: typeof mongoose;
3196
3197 /**
3198 * If this is a discriminator model, baseModelName is the
3199 * name of the base model.
3200 */
3201 baseModelName: string | undefined;
3202
3203 /** Registered discriminators for this model. */
3204 discriminators: { [name: string]: Model<any> } | undefined;
3205
3206 /** The name of the model */
3207 modelName: string;
3208
3209 /**
3210 * Model constructor
3211 * Provides the interface to MongoDB collections as well as creates document instances.
3212 * @param doc values with which to create the document
3213 * @event error If listening to this event, it is emitted when a document
3214 * was saved without passing a callback and an error occurred. If not
3215 * listening, the event bubbles to the connection used to create this Model.
3216 * @event index Emitted after Model#ensureIndexes completes. If an error
3217 * occurred it is passed with the event.
3218 * @event index-single-start Emitted when an individual index starts within
3219 * Model#ensureIndexes. The fields and options being used to build the index
3220 * are also passed with the event.
3221 * @event index-single-done Emitted when an individual index finishes within
3222 * Model#ensureIndexes. If an error occurred it is passed with the event.
3223 * The fields, options, and index name are also passed.
3224 */
3225 new(doc?: any): T;
3226
3227 /**
3228 * Requires a replica set running MongoDB >= 3.6.0. Watches the underlying collection for changes using MongoDB change streams.
3229 * This function does not trigger any middleware. In particular, it does not trigger aggregate middleware.
3230 * @param pipeline See http://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#watch
3231 * @param options See https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#watch
3232 */
3233 watch(
3234 pipeline?: object[],
3235 options?: mongodb.ChangeStreamOptions & { session?: ClientSession },
3236 ): mongodb.ChangeStream;
3237
3238 /**
3239 * Translate any aliases fields/conditions so the final query or document object is pure
3240 * @param raw fields/conditions that may contain aliased keys
3241 * @return the translated 'pure' fields/conditions
3242 */
3243 translateAliases(raw: any): any;
3244
3245 /**
3246 * Sends multiple insertOne, updateOne, updateMany, replaceOne, deleteOne, and/or deleteMany operations to the MongoDB server in one command. This is faster than sending multiple independent operations (like) if you use create()) because with bulkWrite() there is only one round trip to MongoDB.
3247 * Mongoose will perform casting on all operations you provide.
3248 * This function does not trigger any middleware, not save() nor update(). If you need to trigger save() middleware for every document use create() instead.
3249 * @param writes Operations
3250 * @param options Optional settings. See https://mongoosejs.com/docs/api/model.html#model_Model.bulkWrite
3251 * @param cb callback
3252 * @return `BulkWriteOpResult` if the operation succeeds
3253 */
3254 bulkWrite(writes: any[], cb?: (err: any, res: mongodb.BulkWriteOpResultObject) => void): Promise<mongodb.BulkWriteOpResultObject>;
3255 bulkWrite(writes: any[], options?: mongodb.CollectionBulkWriteOptions): Promise<mongodb.BulkWriteOpResultObject>;
3256 bulkWrite(writes: any[], options: mongodb.CollectionBulkWriteOptions, cb: (err: any, res: mongodb.BulkWriteOpResultObject) => void): void;
3257
3258 model<U extends Document>(name: string): Model<U>;
3259
3260 /**
3261 * Creates a Query and specifies a $where condition.
3262 * @param argument is a javascript string or anonymous function
3263 */
3264 $where(argument: string | Function): DocumentQuery<T, T, QueryHelpers> & QueryHelpers;
3265
3266 /**
3267 * Performs aggregations on the models collection.
3268 * If a callback is passed, the aggregate is executed and a Promise is returned.
3269 * If a callback is not passed, the aggregate itself is returned.
3270 * @param aggregations pipeline operator(s) or operator array
3271 */
3272 aggregate<U = any>(aggregations?: any[]): Aggregate<U[]>;
3273 aggregate<U = any>(aggregations: any[], cb: Function): Promise<U[]>;
3274
3275 /** Counts number of matching documents in a database collection. */
3276 count(conditions: FilterQuery<T>, callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
3277
3278 /**
3279 * Counts number of documents matching `criteria` in a database collection.
3280 *
3281 * If you want to count all documents in a large collection,
3282 * use the `estimatedDocumentCount()` instead.
3283 * If you call `countDocuments({})`, MongoDB will always execute
3284 * a full collection scan and **not** use any indexes.
3285 *
3286 * @param {Object} filter
3287 * @param {Function} [callback]
3288 * @return {Query}
3289 */
3290 countDocuments(callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
3291 countDocuments(criteria: FilterQuery<T>, callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
3292
3293 /**
3294 * Estimates the number of documents in the MongoDB collection. Faster than
3295 * using `countDocuments()` for large collections because
3296 * `estimatedDocumentCount()` uses collection metadata rather than scanning
3297 * the entire collection.
3298 *
3299 * @param {Object} [options]
3300 * @param {Function} [callback]
3301 * @return {Query}
3302 */
3303 estimatedDocumentCount(callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
3304 estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query<number> & QueryHelpers;
3305
3306 /**
3307 * Shortcut for saving one or more documents to the database. MyModel.create(docs)
3308 * does new MyModel(doc).save() for every doc in docs.
3309 * Triggers the save() hook.
3310 */
3311 create<TCreate = T>(doc: CreateQuery<TCreate>, options?: SaveOptions): Promise<T>;
3312 create<TCreate = T>(doc: CreateQuery<TCreate>, callback?: (err: any, res: T[]) => void): Promise<T>;
3313 create<TCreate = T>(docs: CreateQuery<TCreate>[], callback?: (err: any, res: T[]) => void): Promise<T[]>;
3314 create<TCreate = T>(docs: CreateQuery<TCreate>[], options?: SaveOptions, callback?: (err: any, res: T[]) => void): Promise<T[]>;
3315 create<TCreate = T>(...docs: CreateQuery<TCreate>[]): Promise<T>;
3316 /**
3317 * Create the collection for this model. By default, if no indexes are specified, mongoose will not create the
3318 * collection for the model until any documents are created. Use this method to create the collection explicitly.
3319 */
3320 createCollection(options?: mongodb.CollectionCreateOptions, cb?: (err: any) => void): Promise<void>;
3321
3322 /**
3323 * Adds a discriminator type.
3324 * @param name discriminator model name
3325 * @param schema discriminator model schema
3326 * @param value the string stored in the `discriminatorKey` property
3327 */
3328 discriminator<U extends Document>(name: string, schema: Schema, value?: string): Model<U>;
3329
3330 /**
3331 * Adds a discriminator type.
3332 * @param name discriminator model name
3333 * @param schema discriminator model schema
3334 * @param value the string stored in the `discriminatorKey` property
3335 */
3336 discriminator<U extends Document, M extends Model<U>>(name: string, schema: Schema, value?: string): M;
3337
3338 /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */
3339 distinct(field: string, callback?: (err: any, res: any[]) => void): Query<any[]> & QueryHelpers;
3340 distinct(field: string, conditions: any,
3341 callback?: (err: any, res: any[]) => void): Query<any[]> & QueryHelpers;
3342
3343 /**
3344 * Makes the indexes in MongoDB match the indexes defined in this model's
3345 * schema. This function will drop any indexes that are not defined in
3346 * the model's schema except the `_id` index, and build any indexes that
3347 * are in your schema but not in MongoDB.
3348 * @param options options to pass to `ensureIndexes()`
3349 * @param callback optional callback
3350 * @return Returns `undefined` if callback is specified, returns a promise if no callback.
3351 */
3352 syncIndexes(options: object | null | undefined, callback: (err: any) => void): void;
3353 syncIndexes(options?: object | null): Promise<void>;
3354
3355 /**
3356 * Lists the indexes currently defined in MongoDB. This may or may not be
3357 * the same as the indexes defined in your schema depending on whether you
3358 * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you
3359 * build indexes manually.
3360 * @param cb optional callback
3361 * @return Returns `undefined` if callback is specified, returns a promise if no callback.
3362 */
3363 listIndexes(callback: (err: any) => void): void;
3364 listIndexes(): Promise<void>;
3365
3366 /**
3367 * Sends ensureIndex commands to mongo for each index declared in the schema.
3368 * @param options internal options
3369 * @param cb optional callback
3370 */
3371 ensureIndexes(callback?: (err: any) => void): Promise<void>;
3372 ensureIndexes(options: any, callback?: (err: any) => void): Promise<void>;
3373
3374 /**
3375 * Similar to ensureIndexes(), except for it uses the createIndex function. The ensureIndex() function checks to see if an index with that name already exists, and, if not, does not attempt to create the index. createIndex() bypasses this check.
3376 * @param cb Optional callback
3377 */
3378 createIndexes(cb?: (err: any) => void): Promise<void>;
3379
3380 /**
3381 * Returns true if at least one document exists in the database that matches
3382 * the given `filter`, and false otherwise.
3383 */
3384 exists(filter: FilterQuery<T>, callback?: (err: any, res: boolean) => void): Promise<boolean>;
3385
3386 /**
3387 * Finds documents.
3388 * @param projection optional fields to return
3389 */
3390 find(callback?: (err: any, res: T[]) => void): DocumentQuery<T[], T, QueryHelpers> & QueryHelpers;
3391 find(conditions: FilterQuery<T>, callback?: (err: any, res: T[]) => void): DocumentQuery<T[], T, QueryHelpers> & QueryHelpers;
3392 find(conditions: FilterQuery<T>, projection?: any | null,
3393 callback?: (err: any, res: T[]) => void): DocumentQuery<T[], T, QueryHelpers> & QueryHelpers;
3394 find(conditions: FilterQuery<T>, projection?: any | null, options?: { lean: true } & Omit<QueryFindOptions, 'lean'>,
3395 callback?: (err: any, res: T[]) => void): Query<DocumentDefinition<T>[]> & QueryHelpers;
3396 find(conditions: FilterQuery<T>, projection?: any | null, options?: QueryFindOptions,
3397 callback?: (err: any, res: T[]) => void): DocumentQuery<T[], T, QueryHelpers> & QueryHelpers;
3398
3399 /**
3400 * Finds a single document by its _id field. findById(id) is almost*
3401 * equivalent to findOne({ _id: id }). findById() triggers findOne hooks.
3402 * @param id value of _id to query by
3403 * @param projection optional fields to return
3404 */
3405 findById(id: any | string | number,
3406 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3407 findById(id: any | string | number, projection: any,
3408 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3409 findById(id: any | string | number, projection: any, options: { lean: true } & Omit<QueryFindBaseOptions, 'lean'>,
3410 callback?: (err: any, res: T | null) => void): Query<DocumentDefinition<T>> & QueryHelpers;
3411 findById(id: any | string | number, projection: any, options: QueryFindBaseOptions,
3412 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3413
3414 /**
3415 * Issue a mongodb findAndModify remove command by a document's _id field.
3416 * findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...).
3417 * Finds a matching document, removes it, passing the found document (if any) to the callback.
3418 * Executes immediately if callback is passed, else a Query object is returned.
3419 *
3420 * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify().
3421 * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set
3422 *
3423 * Note: same signatures as findByIdAndDelete
3424 *
3425 * @param id value of _id to query by
3426 */
3427 findByIdAndRemove(): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3428 findByIdAndRemove(id: any | number | string,
3429 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3430 findByIdAndRemove(id: any | number | string, options: QueryFindOneAndRemoveOptions,
3431 callback?: (err: any, res: mongodb.FindAndModifyWriteOpResultObject<T | null>) => void)
3432 : Query<mongodb.FindAndModifyWriteOpResultObject<T | null>> & QueryHelpers;
3433 findByIdAndRemove(id: any | number | string, options: QueryFindOneAndRemoveOptions, callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3434
3435
3436 /**
3437 * Issue a mongodb findOneAndDelete command by a document's _id field.
3438 * findByIdAndDelete(id, ...) is equivalent to findOneAndDelete({ _id: id }, ...).
3439 * Finds a matching document, removes it, passing the found document (if any) to the callback.
3440 * Executes immediately if callback is passed, else a Query object is returned.
3441 *
3442 * Note: same signatures as findByIdAndRemove
3443 *
3444 * @param id value of _id to query by
3445 */
3446 findByIdAndDelete(): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3447 findByIdAndDelete(id: any | number | string,
3448 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3449 findByIdAndDelete(id: any | number | string, options: QueryFindOneAndRemoveOptions,
3450 callback?: (err: any, res: mongodb.FindAndModifyWriteOpResultObject<T | null>) => void)
3451 : Query<mongodb.FindAndModifyWriteOpResultObject<T | null>> & QueryHelpers;
3452 findByIdAndDelete(id: any | number | string, options: QueryFindOneAndRemoveOptions, callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3453
3454 /**
3455 * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...)
3456 * is equivalent to findOneAndUpdate({ _id: id }, ...).
3457 *
3458 * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify().
3459 * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set
3460 *
3461 * @param id value of _id to query by
3462 */
3463 findByIdAndUpdate(): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3464 findByIdAndUpdate(id: any | number | string, update: UpdateQuery<T>,
3465 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3466 findByIdAndUpdate(id: any | number | string, update: UpdateQuery<T>,
3467 options: { rawResult: true } & { upsert: true } & { new: true } & QueryFindOneAndUpdateOptions,
3468 callback?: (err: any, res: T) => void): DocumentQuery<T, T, QueryHelpers> & QueryHelpers;
3469 findByIdAndUpdate(id: any | number | string, update: UpdateQuery<T>,
3470 options: { upsert: true, new: true } & QueryFindOneAndUpdateOptions,
3471 callback?: (err: any, res: mongodb.FindAndModifyWriteOpResultObject<T>) => void)
3472 : Query<mongodb.FindAndModifyWriteOpResultObject<T>> & QueryHelpers;
3473 findByIdAndUpdate(id: any | number | string, update: UpdateQuery<T>,
3474 options: { rawResult : true } & QueryFindOneAndUpdateOptions,
3475 callback?: (err: any, res: mongodb.FindAndModifyWriteOpResultObject<T | null>) => void)
3476 : Query<mongodb.FindAndModifyWriteOpResultObject<T | null>> & QueryHelpers;
3477 findByIdAndUpdate(id: any | number | string, update: UpdateQuery<T>,
3478 options: { lean: true } & Omit<QueryFindOneAndUpdateOptions, 'lean'>,
3479 callback?: (err: any, res: DocumentDefinition<T>) => void)
3480 : Query<DocumentDefinition<T>> & QueryHelpers;
3481 findByIdAndUpdate(id: any | number | string, update: UpdateQuery<T>,
3482 options: QueryFindOneAndUpdateOptions,
3483 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3484
3485 /**
3486 * Finds one document.
3487 * The conditions are cast to their respective SchemaTypes before the command is sent.
3488 * @param projection optional fields to return
3489 */
3490 findOne(conditions?: FilterQuery<T>,
3491 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3492 findOne(conditions: FilterQuery<T>, projection: any,
3493 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3494 findOne(conditions: FilterQuery<T>, projection: any, options: { lean: true } & Omit<QueryFindBaseOptions, 'lean'>,
3495 callback?: (err: any, res: T | null) => void): Query<DocumentDefinition<T>> & QueryHelpers;
3496 findOne(conditions: FilterQuery<T>, projection: any, options: QueryFindBaseOptions,
3497 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3498
3499 /**
3500 * Issue a mongodb findAndModify remove command.
3501 * Finds a matching document, removes it, passing the found document (if any) to the callback.
3502 * Executes immediately if callback is passed else a Query object is returned.
3503 *
3504 * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify().
3505 * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set
3506 *
3507 * Note: same signatures as findOneAndDelete
3508 *
3509 */
3510 findOneAndRemove(): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3511 findOneAndRemove(conditions: FilterQuery<T>,
3512 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3513 findOneAndRemove(conditions: FilterQuery<T>, options: { rawResult: true } & QueryFindOneAndRemoveOptions,
3514 callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<T | null>, res: any) => void)
3515 : Query<mongodb.FindAndModifyWriteOpResultObject<T | null>> & QueryHelpers;
3516 findOneAndRemove(conditions: FilterQuery<T>, options: QueryFindOneAndRemoveOptions, callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3517
3518 /**
3519 * Issues a mongodb findOneAndDelete command.
3520 * Finds a matching document, removes it, passing the found document (if any) to the
3521 * callback. Executes immediately if callback is passed.
3522 *
3523 * Note: same signatures as findOneAndRemove
3524 *
3525 */
3526 findOneAndDelete(): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3527 findOneAndDelete(conditions: FilterQuery<T>,
3528 callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3529 findOneAndDelete(conditions: FilterQuery<T>, options: { rawResult: true } & QueryFindOneAndRemoveOptions,
3530 callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<T | null>, res: any) => void)
3531 : Query<mongodb.FindAndModifyWriteOpResultObject<T | null>> & QueryHelpers;
3532 findOneAndDelete(conditions: FilterQuery<T>, options: QueryFindOneAndRemoveOptions, callback?: (err: any, res: T | null) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3533
3534 /**
3535 * Issues a mongodb findAndModify update command.
3536 * Finds a matching document, updates it according to the update arg, passing any options,
3537 * and returns the found document (if any) to the callback. The query executes immediately
3538 * if callback is passed else a Query object is returned.
3539 *
3540 * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than the deprecated findAndModify().
3541 * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set
3542 */
3543 findOneAndUpdate(): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3544 findOneAndUpdate(conditions: FilterQuery<T>, update: UpdateQuery<T>,
3545 callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3546 findOneAndUpdate(conditions: FilterQuery<T>, update: UpdateQuery<T>,
3547 options: { rawResult : true } & { upsert: true, new: true } & QueryFindOneAndUpdateOptions,
3548 callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<T>, res: any) => void)
3549 : Query<mongodb.FindAndModifyWriteOpResultObject<T>> & QueryHelpers;
3550 findOneAndUpdate(conditions: FilterQuery<T>, update: UpdateQuery<T>,
3551 options: { upsert: true, new: true } & QueryFindOneAndUpdateOptions,
3552 callback?: (err: any, doc: T, res: any) => void): DocumentQuery<T, T, QueryHelpers> & QueryHelpers;
3553 findOneAndUpdate(conditions: FilterQuery<T>, update: UpdateQuery<T>,
3554 options: { rawResult: true } & QueryFindOneAndUpdateOptions,
3555 callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject<T | null>, res: any) => void)
3556 : Query<mongodb.FindAndModifyWriteOpResultObject<T | null>> & QueryHelpers;
3557 findOneAndUpdate(conditions: FilterQuery<T>, update: UpdateQuery<T>,
3558 options: { lean: true } & Omit<QueryFindOneAndUpdateOptions, 'lean'>,
3559 callback?: (err: any, doc: DocumentDefinition<T>, res: any) => void): Query<DocumentDefinition<T>> & QueryHelpers;
3560 findOneAndUpdate(conditions: FilterQuery<T>, update: UpdateQuery<T>,
3561 options: QueryFindOneAndUpdateOptions,
3562 callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery<T | null, T, QueryHelpers> & QueryHelpers;
3563
3564 /**
3565 * Implements $geoSearch functionality for Mongoose
3566 * @param conditions an object that specifies the match condition (required)
3567 * @param options for the geoSearch, some (near, maxDistance) are required
3568 * @param callback optional callback
3569 */
3570 geoSearch(conditions: any, options: {
3571 /** x,y point to search for */
3572 near: number[];
3573 /** the maximum distance from the point near that a result can be */
3574 maxDistance: number;
3575 /** The maximum number of results to return */
3576 limit?: number;
3577 /** return the raw object instead of the Mongoose Model */
3578 lean?: boolean;
3579 }, callback?: (err: any, res: T[]) => void): DocumentQuery<T[], T, QueryHelpers> & QueryHelpers;
3580
3581 /**
3582 * Shortcut for creating a new Document from existing raw data,
3583 * pre-saved in the DB. The document returned has no paths marked
3584 * as modified initially.
3585 */
3586 hydrate(obj: any): T;
3587
3588 /**
3589 * Shortcut for validating an array of documents and inserting them into
3590 * MongoDB if they're all valid. This function is faster than .create()
3591 * because it only sends one operation to the server, rather than one for each
3592 * document.
3593 * This function does not trigger save middleware.
3594 * @param docs Documents to insert.
3595 * @param options Optional settings.
3596 * @param options.ordered if true, will fail fast on the first error encountered.
3597 * If false, will insert all the documents it can and report errors later.
3598 * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation.
3599 * If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback)
3600 * with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`.
3601 */
3602 insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): Promise<T[]>;
3603 insertMany(docs: any[], options?: { ordered?: boolean, rawResult?: boolean } & ModelOptions, callback?: (error: any, docs: T[]) => void): Promise<T[]>;
3604 insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise<T>;
3605 insertMany(doc: any, options?: { ordered?: boolean, rawResult?: boolean } & ModelOptions, callback?: (error: any, doc: T) => void): Promise<T>;
3606
3607 /**
3608 * Performs any async initialization of this model against MongoDB.
3609 * This function is called automatically, so you don't need to call it.
3610 * This function is also idempotent, so you may call it to get back a promise
3611 * that will resolve when your indexes are finished building as an alternative
3612 * to `MyModel.on('index')`
3613 * @param callback optional
3614 */
3615 init(callback?: (err: any) => void): Promise<T>;
3616
3617 /**
3618 * Executes a mapReduce command.
3619 * @param o an object specifying map-reduce options
3620 * @param callbackoptional callback
3621 */
3622 mapReduce<Key, Value>(
3623 o: ModelMapReduceOption<T, Key, Value>,
3624 callback?: (err: any, res: any) => void
3625 ): Promise<any>;
3626
3627 /**
3628 * Populates document references.
3629 * @param docs Either a single document or array of documents to populate.
3630 * @param options A hash of key/val (path, options) used for population.
3631 * @param callback Optional callback, executed upon completion. Receives err and the doc(s).
3632 */
3633 populate(docs: any[], options: ModelPopulateOptions | ModelPopulateOptions[],
3634 callback?: (err: any, res: T[]) => void): Promise<T[]>;
3635 populate<T>(docs: any, options: ModelPopulateOptions | ModelPopulateOptions[],
3636 callback?: (err: any, res: T) => void): Promise<T>;
3637
3638 /** Removes documents from the collection. */
3639 remove(conditions: FilterQuery<T>, callback?: (err: any) => void): Query<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }> & QueryHelpers;
3640 deleteOne(conditions: FilterQuery<T>, callback?: (err: any) => void): Query<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }> & QueryHelpers;
3641 deleteOne(conditions: FilterQuery<T>, options: ModelOptions, callback?: (err: any) => void): Query<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }> & QueryHelpers;
3642 deleteMany(conditions: FilterQuery<T>, callback?: (err: any) => void): Query<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }> & QueryHelpers;
3643 deleteMany(conditions: FilterQuery<T>, options: ModelOptions, callback?: (err: any) => void): Query<mongodb.DeleteWriteOpResultObject['result'] & { deletedCount?: number }> & QueryHelpers;
3644
3645 /**
3646 * Same as update(), except MongoDB replace the existing document with the given document (no atomic operators like $set).
3647 * This function triggers the following middleware: replaceOne
3648 */
3649 replaceOne(conditions: FilterQuery<T>, replacement: any, callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;
3650
3651 /**
3652 * Updates documents in the database without returning them.
3653 * All update values are cast to their appropriate SchemaTypes before being sent.
3654 */
3655 update(conditions: FilterQuery<T>, doc: UpdateQuery<T>,
3656 callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;
3657 update(conditions: FilterQuery<T>, doc: UpdateQuery<T>, options: ModelUpdateOptions,
3658 callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;
3659 updateOne(conditions: FilterQuery<T>, doc: UpdateQuery<T>,
3660 callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;
3661 updateOne(conditions: FilterQuery<T>, doc: UpdateQuery<T>, options: ModelUpdateOptions,
3662 callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;
3663 updateMany(conditions: FilterQuery<T>, doc: UpdateQuery<T>,
3664 callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;
3665 updateMany(conditions: FilterQuery<T>, doc: UpdateQuery<T>, options: ModelUpdateOptions,
3666 callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;
3667
3668 /** Creates a Query, applies the passed conditions, and returns the Query. */
3669 where(path: string, val?: any): Query<any> & QueryHelpers;
3670 }
3671
3672 class Document {}
3673 interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties {
3674 /** Signal that we desire an increment of this documents version. */
3675 increment(): this;
3676
3677 /**
3678 * Returns another Model instance.
3679 * @param name model name
3680 */
3681 model<T extends Document>(name: string): Model<T>;
3682
3683 /** Override whether mongoose thinks this doc is deleted or not */
3684 $isDeleted(isDeleted: boolean): void;
3685 /** whether mongoose thinks this doc is deleted. */
3686 $isDeleted(): boolean;
3687
3688 /**
3689 * Removes this document from the db.
3690 * @param fn optional callback
3691 */
3692 remove(fn?: (err: any, product: this) => void): Promise<this>;
3693
3694 /**
3695 * Deletes the document from the db.
3696 * @param fn optional callback
3697 */
3698 deleteOne(fn?: (err: any, product: this) => void): Promise<this>;
3699
3700 /**
3701 * Saves this document.
3702 * @param options options optional options
3703 * @param options.safe overrides schema's safe option
3704 * @param options.validateBeforeSave set to false to save without validating.
3705 * @param fn optional callback
3706 */
3707 save(options?: SaveOptions, fn?: (err: any, product: this) => void): Promise<this>;
3708 save(fn?: (err: any, product: this) => void): Promise<this>;
3709
3710 /**
3711 * Version using default version key. See http://mongoosejs.com/docs/guide.html#versionKey
3712 * If you're using another key, you will have to access it using []: doc[_myVersionKey]
3713 */
3714 __v?: number;
3715 }
3716
3717 interface SaveOptions {
3718 checkKeys?: boolean;
3719 safe?: boolean | WriteConcern;
3720 validateBeforeSave?: boolean;
3721 validateModifiedOnly?: boolean;
3722 j?: boolean;
3723 session?: ClientSession;
3724 timestamps?: boolean;
3725 w?: number | string;
3726 wtimeout?: number;
3727 }
3728
3729 interface WriteConcern {
3730 j?: boolean;
3731 w?: number | 'majority' | TagSet;
3732 wtimeout?: number;
3733 }
3734
3735 interface TagSet {
3736 [k: string]: string;
3737 }
3738
3739 interface ModelProperties {
3740 /** Collection the model uses. */
3741 collection: Collection;
3742
3743 /** Connection the model uses. */
3744 db: Connection;
3745
3746 /** Schema the model uses. */
3747 schema: Schema;
3748 }
3749
3750 /** https://mongoosejs.com/docs/api.html#query_Query-setOptions */
3751 interface ModelOptions {
3752 session?: ClientSession | null;
3753 }
3754
3755 interface QueryPopulateOptions {
3756 /** space delimited path(s) to populate */
3757 path: string;
3758 /** optional fields to select */
3759 select?: any;
3760 /** optional query conditions to match */
3761 match?: any;
3762 /** optional model to use for population */
3763 model?: string | Model<any>;
3764 /** optional query options like sort, limit, etc */
3765 options?: any;
3766 /** deep populate */
3767 populate?: QueryPopulateOptions | QueryPopulateOptions[];
3768 }
3769
3770 interface ModelPopulateOptions extends QueryPopulateOptions {
3771 /** optional, if true Mongoose will always set path to an array. Inferred from schema by default */
3772 justOne?: boolean;
3773 }
3774
3775 interface ModelUpdateOptions extends ModelOptions {
3776 /** safe mode (defaults to value set in schema (true)) */
3777 safe?: boolean;
3778 /** whether to create the doc if it doesn't match (false) */
3779 upsert?: boolean;
3780 /** whether multiple documents should be updated (false) */
3781 multi?: boolean;
3782 /**
3783 * If true, runs update validators on this command. Update validators validate
3784 * the update operation against the model's schema.
3785 */
3786 runValidators?: boolean;
3787 /**
3788 * If this and upsert are true, mongoose will apply the defaults specified in the
3789 * model's schema if a new document is created. This option only works on MongoDB >= 2.4
3790 * because it relies on MongoDB's $setOnInsert operator.
3791 */
3792 setDefaultsOnInsert?: boolean;
3793 /** overrides the strict option for this update */
3794 strict?: boolean | "throw";
3795 /** disables update-only mode, allowing you to overwrite the doc (false) */
3796 overwrite?: boolean;
3797 /**
3798 * Only update elements that match the arrayFilters conditions in the document or documents that match the query conditions.
3799 */
3800 arrayFilters?: { [key: string]: any }[];
3801 /** other options */
3802 [other: string]: any;
3803 /**
3804 * by default, mongoose only returns the first error that occurred in casting the query.
3805 * Turn on this option to aggregate all the cast errors.
3806 */
3807 multipleCastError?: boolean;
3808 }
3809
3810 interface ModelMapReduceOption<T, Key, Val> {
3811 map: Function | string;
3812 reduce: (key: Key, vals: T[]) => Val;
3813 /** query filter object. */
3814 query?: any;
3815 /** sort input objects using this key */
3816 sort?: any;
3817 /** max number of documents */
3818 limit?: number;
3819 /** keep temporary data default: false */
3820 keeptemp?: boolean;
3821 /** finalize function */
3822 finalize?: (key: Key, val: Val) => Val;
3823 /** scope variables exposed to map/reduce/finalize during execution */
3824 scope?: any;
3825 /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */
3826 jsMode?: boolean;
3827 /** provide statistics on job execution time. default: false */
3828 verbose?: boolean;
3829 readPreference?: string;
3830 /** sets the output target for the map reduce job. default: {inline: 1} */
3831 out?: {
3832 /** the results are returned in an array */
3833 inline?: number;
3834 /**
3835 * {replace: 'collectionName'} add the results to collectionName: the
3836 * results replace the collection
3837 */
3838 replace?: string;
3839 /**
3840 * {reduce: 'collectionName'} add the results to collectionName: if
3841 * dups are detected, uses the reducer / finalize functions
3842 */
3843 reduce?: string;
3844 /**
3845 * {merge: 'collectionName'} add the results to collectionName: if
3846 * dups exist the new docs overwrite the old
3847 */
3848 merge?: string;
3849 };
3850 }
3851
3852 interface MapReduceResult<Key, Val> {
3853 _id: Key;
3854 value: Val;
3855 }
3856
3857 /*
3858 * section collection.js
3859 * http://mongoosejs.com/docs/api.html#collection-js
3860 */
3861 interface CollectionBase extends mongodb.Collection {
3862 /*
3863 * Abstract methods. Some of these are already defined on the
3864 * mongodb.Collection interface so they've been commented out.
3865 */
3866 ensureIndex(...args: any[]): any;
3867 //find(...args: any[]): any;
3868 findAndModify(...args: any[]): any;
3869 //findOne(...args: any[]): any;
3870 getIndexes(...args: any[]): any;
3871 //insert(...args: any[]): any;
3872 //mapReduce(...args: any[]): any;
3873 //save(...args: any[]): any;
3874 //update(...args: any[]): any;
3875
3876 /** The collection name */
3877 collectionName: string;
3878 /** The Connection instance */
3879 conn: Connection;
3880 /** The collection name */
3881 name: string;
3882 }
3883}
3884
\No newline at end of file