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