mongoose 6.3.4 → 6.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.eslintrc.json +1 -1
  2. package/dist/browser.umd.js +1 -1
  3. package/lgtm.yml +12 -0
  4. package/lib/cast/objectid.js +3 -2
  5. package/lib/connection.js +3 -2
  6. package/lib/document.js +37 -24
  7. package/lib/error/index.js +2 -2
  8. package/lib/helpers/clone.js +7 -1
  9. package/lib/helpers/common.js +3 -4
  10. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +2 -2
  11. package/lib/helpers/isBsonType.js +5 -3
  12. package/lib/helpers/path/setDottedPath.js +14 -1
  13. package/lib/helpers/schematype/handleImmutable.js +2 -1
  14. package/lib/helpers/topology/isAtlas.js +15 -2
  15. package/lib/helpers/update/applyTimestampsToChildren.js +4 -0
  16. package/lib/helpers/update/castArrayFilters.js +3 -0
  17. package/lib/index.js +4 -3
  18. package/lib/options/SchemaTypeOptions.js +13 -0
  19. package/lib/query.js +4 -1
  20. package/lib/schema/SubdocumentPath.js +8 -1
  21. package/lib/schema/decimal128.js +4 -4
  22. package/lib/schema/documentarray.js +2 -4
  23. package/lib/schema/map.js +8 -0
  24. package/lib/schema/objectid.js +4 -3
  25. package/lib/schema/string.js +2 -2
  26. package/lib/schema.js +33 -2
  27. package/lib/schematype.js +1 -0
  28. package/lib/types/DocumentArray/methods/index.js +3 -3
  29. package/lib/types/array/methods/index.js +3 -3
  30. package/lib/types/map.js +4 -4
  31. package/lib/utils.js +3 -4
  32. package/package.json +17 -15
  33. package/types/aggregate.d.ts +3 -4
  34. package/types/callback.d.ts +8 -0
  35. package/types/collection.d.ts +46 -0
  36. package/types/connection.d.ts +91 -71
  37. package/types/document.d.ts +1 -1
  38. package/types/error.d.ts +5 -1
  39. package/types/helpers.d.ts +32 -0
  40. package/types/index.d.ts +32 -1859
  41. package/types/indizes.d.ts +98 -0
  42. package/types/middlewares.d.ts +14 -0
  43. package/types/models.d.ts +419 -0
  44. package/types/populate.d.ts +40 -0
  45. package/types/query.d.ts +637 -0
  46. package/types/schematypes.d.ts +427 -0
  47. package/types/session.d.ts +36 -0
  48. package/types/types.d.ts +102 -0
  49. package/types/utility.d.ts +13 -0
  50. package/types/validation.d.ts +32 -0
  51. package/.lgtm.yml +0 -3
  52. package/CHANGELOG.md +0 -7300
  53. package/History.md +0 -1
package/types/index.d.ts CHANGED
@@ -1,11 +1,24 @@
1
1
  /// <reference path="./aggregate.d.ts" />
2
+ /// <reference path="./callback.d.ts" />
3
+ /// <reference path="./collection.d.ts" />
2
4
  /// <reference path="./connection.d.ts" />
3
5
  /// <reference path="./cursor.d.ts" />
4
6
  /// <reference path="./document.d.ts" />
5
7
  /// <reference path="./error.d.ts" />
8
+ /// <reference path="./helpers.d.ts" />
9
+ /// <reference path="./middlewares.d.ts" />
10
+ /// <reference path="./indizes.d.ts" />
11
+ /// <reference path="./models.d.ts" />
6
12
  /// <reference path="./mongooseoptions.d.ts" />
7
13
  /// <reference path="./pipelinestage.d.ts" />
14
+ /// <reference path="./populate.d.ts" />
15
+ /// <reference path="./query.d.ts" />
8
16
  /// <reference path="./schemaoptions.d.ts" />
17
+ /// <reference path="./schematypes.d.ts" />
18
+ /// <reference path="./session.d.ts" />
19
+ /// <reference path="./types.d.ts" />
20
+ /// <reference path="./utility.d.ts" />
21
+ /// <reference path="./validation.d.ts" />
9
22
 
10
23
  declare class NativeDate extends global.Date { }
11
24
 
@@ -14,25 +27,6 @@ declare module 'mongoose' {
14
27
  import mongodb = require('mongodb');
15
28
  import mongoose = require('mongoose');
16
29
 
17
- /** The Mongoose Date [SchemaType](/docs/schematypes.html). */
18
- export type Date = Schema.Types.Date;
19
-
20
- /**
21
- * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for
22
- * declaring paths in your schema that should be
23
- * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
24
- * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128`
25
- * instead.
26
- */
27
- export type Decimal128 = Schema.Types.Decimal128;
28
-
29
- /**
30
- * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for
31
- * declaring paths in your schema that Mongoose's change tracking, casting,
32
- * and validation should ignore.
33
- */
34
- export type Mixed = Schema.Types.Mixed;
35
-
36
30
  export type Mongoose = typeof mongoose;
37
31
 
38
32
  /**
@@ -41,51 +35,9 @@ declare module 'mongoose' {
41
35
  */
42
36
  export const Mongoose: new (options?: MongooseOptions | null) => Mongoose;
43
37
 
44
- /**
45
- * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for
46
- * declaring paths in your schema that Mongoose should cast to numbers.
47
- */
48
- export type Number = Schema.Types.Number;
49
-
50
- /**
51
- * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for
52
- * declaring paths in your schema that should be
53
- * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/).
54
- * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId`
55
- * instead.
56
- */
57
- export type ObjectId = Schema.Types.ObjectId;
58
-
59
38
  export let Promise: any;
60
39
  export const PromiseProvider: any;
61
40
 
62
- /** The various Mongoose SchemaTypes. */
63
- export const SchemaTypes: typeof Schema.Types;
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: CallbackWithoutResult): void;
67
- export function connect(uri: string, callback: CallbackWithoutResult): void;
68
- export function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
69
-
70
- /**
71
- * Makes the indexes in MongoDB match the indexes defined in every model's
72
- * schema. This function will drop any indexes that are not defined in
73
- * the model's schema except the `_id` index, and build any indexes that
74
- * are in your schema but not in MongoDB.
75
- */
76
- export function syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
77
- export function syncIndexes(options: SyncIndexesOptions | null, callback: Callback<ConnectionSyncIndexesResult>): void;
78
-
79
- /* Tells `sanitizeFilter()` to skip the given object when filtering out potential query selector injection attacks.
80
- * Use this method when you have a known query selector that you want to use. */
81
- export function trusted<T>(obj: T): T;
82
-
83
- /** The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). */
84
- export const connection: Connection;
85
-
86
- /** An array containing all connections associated with this Mongoose instance. */
87
- export const connections: Connection[];
88
-
89
41
  /**
90
42
  * Can be extended to explicitly type specific models.
91
43
  */
@@ -96,11 +48,6 @@ declare module 'mongoose' {
96
48
  /** An array containing all models associated with this Mongoose instance. */
97
49
  export const models: Models;
98
50
 
99
- /** Creates a Connection instance. */
100
- export function createConnection(uri: string, options: ConnectOptions, callback: Callback<Connection>): void;
101
- export function createConnection(uri: string, options?: ConnectOptions): Connection;
102
- export function createConnection(): Connection;
103
-
104
51
  /**
105
52
  * Removes the model named `name` from the default connection, if it exists.
106
53
  * You can use this function to clean up any models you created in your tests to
@@ -108,33 +55,16 @@ declare module 'mongoose' {
108
55
  */
109
56
  export function deleteModel(name: string | RegExp): Mongoose;
110
57
 
111
- export function disconnect(): Promise<void>;
112
- export function disconnect(cb: CallbackWithoutResult): void;
113
-
114
58
  /** Gets mongoose options */
115
59
  export function get<K extends keyof MongooseOptions>(key: K): MongooseOptions[K];
116
60
 
117
61
  /* ! ignore */
118
62
  export type CompileModelOptions = { overwriteModels?: boolean, connection?: Connection };
119
63
 
120
- /**
121
- * Returns true if Mongoose can cast the given value to an ObjectId, or
122
- * false otherwise.
123
- */
124
- export function isValidObjectId(v: Types.ObjectId): true;
125
- export function isValidObjectId(v: any): boolean;
126
-
127
- /**
128
- * Returns true if the given value is a Mongoose ObjectId (using `instanceof`) or if the
129
- * given value is a 24 character hex string, which is the most commonly used string representation
130
- * of an ObjectId.
131
- */
132
- export function isObjectIdOrHexString(v: any): boolean;
133
-
134
64
  export function model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
135
65
  export function model<T, U, TQueryHelpers = {}>(
136
66
  name: string,
137
- schema?: Schema<T, U, TQueryHelpers>,
67
+ schema?: Schema<T, U, {}, TQueryHelpers>,
138
68
  collection?: string,
139
69
  options?: CompileModelOptions
140
70
  ): U;
@@ -145,13 +75,6 @@ declare module 'mongoose' {
145
75
  /** The node-mongodb-native driver Mongoose uses. */
146
76
  export const mongo: typeof mongodb;
147
77
 
148
- /**
149
- * Mongoose uses this function to get the current time when setting
150
- * [timestamps](/docs/guide.html#timestamps). You may stub out this function
151
- * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing.
152
- */
153
- export function now(): NativeDate;
154
-
155
78
  /** Declares a global plugin executed on all Schemas. */
156
79
  export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Mongoose;
157
80
 
@@ -161,74 +84,9 @@ declare module 'mongoose' {
161
84
  /** Sets mongoose options */
162
85
  export function set<K extends keyof MongooseOptions>(key: K, value: MongooseOptions[K]): Mongoose;
163
86
 
164
- /**
165
- * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
166
- * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
167
- * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
168
- */
169
- export function startSession(options?: mongodb.ClientSessionOptions): Promise<mongodb.ClientSession>;
170
- export function startSession(options: mongodb.ClientSessionOptions, cb: Callback<mongodb.ClientSession>): void;
171
-
172
87
  /** The Mongoose version */
173
88
  export const version: string;
174
89
 
175
- export type CastError = Error.CastError;
176
- export type SyncIndexesError = Error.SyncIndexesError;
177
-
178
- export type ClientSession = mongodb.ClientSession;
179
-
180
- /*
181
- * section collection.js
182
- * http://mongoosejs.com/docs/api.html#collection-js
183
- */
184
- export interface CollectionBase<T extends mongodb.Document> extends mongodb.Collection<T> {
185
- /*
186
- * Abstract methods. Some of these are already defined on the
187
- * mongodb.Collection interface so they've been commented out.
188
- */
189
- ensureIndex(...args: any[]): any;
190
- findAndModify(...args: any[]): any;
191
- getIndexes(...args: any[]): any;
192
-
193
- /** The collection name */
194
- collectionName: string;
195
- /** The Connection instance */
196
- conn: Connection;
197
- /** The collection name */
198
- name: string;
199
- }
200
-
201
- /*
202
- * section drivers/node-mongodb-native/collection.js
203
- * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js
204
- */
205
- export let Collection: Collection;
206
- export interface Collection<T extends mongodb.Document = mongodb.Document> extends CollectionBase<T> {
207
- /**
208
- * Collection constructor
209
- * @param name name of the collection
210
- * @param conn A MongooseConnection instance
211
- * @param opts optional collection options
212
- */
213
- // eslint-disable-next-line @typescript-eslint/no-misused-new
214
- new(name: string, conn: Connection, opts?: any): Collection<T>;
215
- /** Formatter for debug print args */
216
- $format(arg: any): string;
217
- /** Debug print helper */
218
- $print(name: any, i: any, args: any[]): void;
219
- /** Retrieves information about this collections indexes. */
220
- getIndexes(): any;
221
- }
222
-
223
- /** A list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. */
224
- export type pathsToValidate = string[] | string;
225
-
226
- export interface AcceptsDiscriminator {
227
- /** Adds a discriminator type. */
228
- discriminator<D>(name: string | number, schema: Schema, value?: string | number | ObjectId): Model<D>;
229
- discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string | number | ObjectId): U;
230
- }
231
-
232
90
  export type AnyKeys<T> = { [P in keyof T]?: T[P] | any };
233
91
  export interface AnyObject {
234
92
  [k: string]: any
@@ -237,574 +95,10 @@ declare module 'mongoose' {
237
95
 
238
96
  export type HydratedDocument<DocType, TMethodsAndOverrides = {}, TVirtuals = {}> = DocType extends Document ? Require_id<DocType> : (Document<unknown, any, DocType> & Require_id<DocType> & TVirtuals & TMethodsAndOverrides);
239
97
 
240
- interface MongooseBulkWriteOptions {
241
- skipValidation?: boolean;
242
- }
243
-
244
- interface IndexesDiff {
245
- /** Indexes that would be created in mongodb. */
246
- toCreate: Array<any>
247
- /** Indexes that would be dropped in mongodb. */
248
- toDrop: Array<any>
249
- }
250
-
251
- export interface ModifyResult<T> {
252
- value: Require_id<T> | null;
253
- /** see https://www.mongodb.com/docs/manual/reference/command/findAndModify/#lasterrorobject */
254
- lastErrorObject?: {
255
- updatedExisting?: boolean;
256
- upserted?: mongodb.ObjectId;
257
- };
258
- ok: 0 | 1;
259
- }
260
-
261
- export const Model: Model<any>;
262
- export interface Model<T, TQueryHelpers = {}, TMethodsAndOverrides = {}, TVirtuals = {}> extends NodeJS.EventEmitter, AcceptsDiscriminator {
263
- new <DocType = AnyKeys<T> & AnyObject>(doc?: DocType, fields?: any | null, options?: boolean | AnyObject): HydratedDocument<T, TMethodsAndOverrides, TVirtuals>;
264
-
265
- aggregate<R = any>(pipeline?: PipelineStage[], options?: mongodb.AggregateOptions, callback?: Callback<R[]>): Aggregate<Array<R>>;
266
- aggregate<R = any>(pipeline: PipelineStage[], cb: Function): Aggregate<Array<R>>;
267
-
268
- /** Base Mongoose instance the model uses. */
269
- base: Mongoose;
270
-
271
- /**
272
- * If this is a discriminator model, `baseModelName` is the name of
273
- * the base model.
274
- */
275
- baseModelName: string | undefined;
276
-
277
- /**
278
- * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`,
279
- * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one
280
- * command. This is faster than sending multiple independent operations (e.g.
281
- * if you use `create()`) because with `bulkWrite()` there is only one network
282
- * round trip to the MongoDB server.
283
- */
284
- bulkWrite(writes: Array<any>, options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions): Promise<mongodb.BulkWriteResult>;
285
- bulkWrite(writes: Array<any>, options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions, cb?: Callback<mongodb.BulkWriteResult>): void;
286
-
287
- /**
288
- * Sends multiple `save()` calls in a single `bulkWrite()`. This is faster than
289
- * sending multiple `save()` calls because with `bulkSave()` there is only one
290
- * network round trip to the MongoDB server.
291
- */
292
- bulkSave(documents: Array<Document>, options?: mongodb.BulkWriteOptions): Promise<mongodb.BulkWriteResult>;
293
-
294
- /** Collection the model uses. */
295
- collection: Collection;
296
-
297
- /** Creates a `count` query: counts the number of documents that match `filter`. */
298
- count(callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
299
- count(filter: FilterQuery<T>, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
300
-
301
- /** Creates a `countDocuments` query: counts the number of documents that match `filter`. */
302
- countDocuments(callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
303
- countDocuments(filter: FilterQuery<T>, options?: QueryOptions<T>, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
304
-
305
- /** Creates a new document or documents */
306
- create(docs: (AnyKeys<T> | AnyObject)[], options?: SaveOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
307
- create(docs: (AnyKeys<T> | AnyObject)[], callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>): void;
308
- create(doc: AnyKeys<T> | AnyObject): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
309
- create(doc: AnyKeys<T> | AnyObject, callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>): void;
310
- create<DocContents = AnyKeys<T>>(docs: DocContents[], options?: SaveOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
311
- create<DocContents = AnyKeys<T>>(docs: DocContents[], callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>): void;
312
- create<DocContents = AnyKeys<T>>(doc: DocContents): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
313
- create<DocContents = AnyKeys<T>>(...docs: DocContents[]): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
314
- create<DocContents = AnyKeys<T>>(doc: DocContents, callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>): void;
315
-
316
- /**
317
- * Create the collection for this model. By default, if no indexes are specified,
318
- * mongoose will not create the collection for the model until any documents are
319
- * created. Use this method to create the collection explicitly.
320
- */
321
- createCollection<T extends mongodb.Document>(options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>): Promise<mongodb.Collection<T>>;
322
- createCollection<T extends mongodb.Document>(options: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'> | null, callback: Callback<mongodb.Collection<T>>): void;
323
-
324
- /**
325
- * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)
326
- * function.
327
- */
328
- createIndexes(callback?: CallbackWithoutResult): Promise<void>;
329
- createIndexes(options?: any, callback?: CallbackWithoutResult): Promise<void>;
330
-
331
- /** Connection the model uses. */
332
- db: Connection;
333
-
334
- /**
335
- * Deletes all of the documents that match `conditions` from the collection.
336
- * Behaves like `remove()`, but deletes all documents that match `conditions`
337
- * regardless of the `single` option.
338
- */
339
- deleteMany(filter?: FilterQuery<T>, options?: QueryOptions<T>, callback?: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
340
- deleteMany(filter: FilterQuery<T>, callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
341
- deleteMany(callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
342
-
343
- /**
344
- * Deletes the first document that matches `conditions` from the collection.
345
- * Behaves like `remove()`, but deletes at most one document regardless of the
346
- * `single` option.
347
- */
348
- deleteOne(filter?: FilterQuery<T>, options?: QueryOptions<T>, callback?: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
349
- deleteOne(filter: FilterQuery<T>, callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
350
- deleteOne(callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
351
-
352
- /**
353
- * Sends `createIndex` commands to mongo for each index declared in the schema.
354
- * The `createIndex` commands are sent in series.
355
- */
356
- ensureIndexes(callback?: CallbackWithoutResult): Promise<void>;
357
- ensureIndexes(options?: any, callback?: CallbackWithoutResult): Promise<void>;
358
-
359
- /**
360
- * Event emitter that reports any errors that occurred. Useful for global error
361
- * handling.
362
- */
363
- events: NodeJS.EventEmitter;
364
-
365
- /**
366
- * Finds a single document by its _id field. `findById(id)` is almost*
367
- * equivalent to `findOne({ _id: id })`. If you want to query by a document's
368
- * `_id`, use `findById()` instead of `findOne()`.
369
- */
370
- findById<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
371
- id: any,
372
- projection?: ProjectionType<T> | null,
373
- options?: QueryOptions<T> | null,
374
- callback?: Callback<ResultDoc | null>
375
- ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
376
- findById<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
377
- id: any,
378
- projection?: ProjectionType<T> | null,
379
- callback?: Callback<ResultDoc | null>
380
- ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
381
-
382
- /** Finds one document. */
383
- findOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
384
- filter?: FilterQuery<T>,
385
- projection?: ProjectionType<T> | null,
386
- options?: QueryOptions<T> | null,
387
- callback?: Callback<ResultDoc | null>
388
- ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
389
- findOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
390
- filter?: FilterQuery<T>,
391
- projection?: ProjectionType<T> | null,
392
- callback?: Callback<ResultDoc | null>
393
- ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
394
- findOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
395
- filter?: FilterQuery<T>,
396
- callback?: Callback<ResultDoc | null>
397
- ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
398
-
399
- /**
400
- * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
401
- * The document returned has no paths marked as modified initially.
402
- */
403
- hydrate(obj: any): HydratedDocument<T, TMethodsAndOverrides, TVirtuals>;
404
-
405
- /**
406
- * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/),
407
- * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off.
408
- * Mongoose calls this function automatically when a model is created using
409
- * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or
410
- * [`connection.model()`](/docs/api.html#connection_Connection-model), so you
411
- * don't need to call it.
412
- */
413
- init(callback?: CallbackWithoutResult): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
414
-
415
- /** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */
416
- insertMany(docs: Array<AnyKeys<T> | AnyObject>, options: InsertManyOptions & { rawResult: true }): Promise<InsertManyResult<T>>;
417
- insertMany(docs: Array<AnyKeys<T> | AnyObject>, options?: InsertManyOptions): Promise<Array<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>>;
418
- insertMany(doc: AnyKeys<T> | AnyObject, options: InsertManyOptions & { rawResult: true }): Promise<InsertManyResult<T>>;
419
- insertMany(doc: AnyKeys<T> | AnyObject, options?: InsertManyOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
420
- insertMany(doc: AnyKeys<T> | AnyObject, options?: InsertManyOptions, callback?: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[] | InsertManyResult<T>>): void;
421
- insertMany(docs: Array<AnyKeys<T> | AnyObject>, options?: InsertManyOptions, callback?: Callback<Array<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>> | InsertManyResult<T>>): void;
422
-
423
- /**
424
- * Lists the indexes currently defined in MongoDB. This may or may not be
425
- * the same as the indexes defined in your schema depending on whether you
426
- * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you
427
- * build indexes manually.
428
- */
429
- listIndexes(callback: Callback<Array<any>>): void;
430
- listIndexes(): Promise<Array<any>>;
431
-
432
- /** The name of the model */
433
- modelName: string;
434
-
435
- /** Populates document references. */
436
- populate(docs: Array<any>, options: PopulateOptions | Array<PopulateOptions> | string,
437
- callback?: Callback<(HydratedDocument<T, TMethodsAndOverrides, TVirtuals>)[]>): Promise<Array<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>>;
438
- populate(doc: any, options: PopulateOptions | Array<PopulateOptions> | string,
439
- callback?: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
440
-
441
- /**
442
- * Makes the indexes in MongoDB match the indexes defined in this model's
443
- * schema. This function will drop any indexes that are not defined in
444
- * the model's schema except the `_id` index, and build any indexes that
445
- * are in your schema but not in MongoDB.
446
- */
447
- syncIndexes(options?: Record<string, unknown>): Promise<Array<string>>;
448
- syncIndexes(options: Record<string, unknown> | null, callback: Callback<Array<string>>): void;
449
-
450
- /**
451
- * Does a dry-run of Model.syncIndexes(), meaning that
452
- * the result of this function would be the result of
453
- * Model.syncIndexes().
454
- */
455
- diffIndexes(options?: Record<string, unknown>): Promise<IndexesDiff>
456
- diffIndexes(options: Record<string, unknown> | null, callback: (err: CallbackError, diff: IndexesDiff) => void): void
457
-
458
- /**
459
- * Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
460
- * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
461
- * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
462
- * */
463
- startSession(options?: mongodb.ClientSessionOptions, cb?: Callback<mongodb.ClientSession>): Promise<mongodb.ClientSession>;
464
-
465
- /** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */
466
- validate(callback?: CallbackWithoutResult): Promise<void>;
467
- validate(optional: any, callback?: CallbackWithoutResult): Promise<void>;
468
- validate(optional: any, pathsToValidate: pathsToValidate, callback?: CallbackWithoutResult): Promise<void>;
469
-
470
- /** Watches the underlying collection for changes using [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). */
471
- watch<ResultType extends mongodb.Document = any>(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
472
-
473
- /** Adds a `$where` clause to this query */
474
- $where(argument: string | Function): QueryWithHelpers<Array<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
475
-
476
- /** Registered discriminators for this model. */
477
- discriminators: { [name: string]: Model<any> } | undefined;
478
-
479
- /** Translate any aliases fields/conditions so the final query or document object is pure */
480
- translateAliases(raw: any): any;
481
-
482
- /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
483
- distinct<ReturnType = any>(field: string, filter?: FilterQuery<T>, callback?: Callback<number>): QueryWithHelpers<Array<ReturnType>, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
484
-
485
- /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
486
- estimatedDocumentCount(options?: QueryOptions<T>, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
487
-
488
- /**
489
- * Returns a document with its `_id` if at least one document exists in the database that matches
490
- * the given `filter`, and `null` otherwise.
491
- */
492
- exists(filter: FilterQuery<T>): QueryWithHelpers<Pick<Document<T>, '_id'> | null, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
493
- exists(filter: FilterQuery<T>, callback: Callback<Pick<Document<T>, '_id'> | null>): QueryWithHelpers<Pick<Document<T>, '_id'> | null, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
494
-
495
- /** Creates a `find` query: gets a list of documents that match `filter`. */
496
- find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
497
- find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
498
- filter: FilterQuery<T>,
499
- projection?: ProjectionType<T> | null,
500
- callback?: Callback<ResultDoc[]>
501
- ): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
502
- find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
503
- find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, projection?: ProjectionType<T> | null, options?: QueryOptions<T> | null, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
504
-
505
- /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
506
- findByIdAndDelete<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
507
-
508
- /** Creates a `findByIdAndRemove` query, filtering by the given `_id`. */
509
- findByIdAndRemove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
510
-
511
- /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
512
- findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions<T> & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
513
- findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions<T> & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
514
- findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, update?: UpdateQuery<T>, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
515
- findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, callback: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
516
-
517
- /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
518
- findOneAndDelete<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
519
-
520
- /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
521
- findOneAndRemove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
522
-
523
- /** Creates a `findOneAndReplace` query: atomically finds the given document and replaces it with `replacement`. */
524
- findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, replacement: T | AnyObject, options: QueryOptions<T> & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
525
- findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
526
-
527
- /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
528
- findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
529
- filter: FilterQuery<T>,
530
- update: UpdateQuery<T>,
531
- options: QueryOptions<T> & { rawResult: true },
532
- callback?: (err: CallbackError, doc: any, res: any) => void
533
- ): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
534
- findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
535
- filter: FilterQuery<T>,
536
- update: UpdateQuery<T>,
537
- options: QueryOptions<T> & { upsert: true } & ReturnsNewDoc,
538
- callback?: (err: CallbackError, doc: ResultDoc, res: any) => void
539
- ): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
540
- findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
541
- filter?: FilterQuery<T>,
542
- update?: UpdateQuery<T>,
543
- options?: QueryOptions<T> | null,
544
- callback?: (err: CallbackError, doc: T | null, res: any) => void
545
- ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
546
-
547
- geoSearch<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
548
- filter?: FilterQuery<T>,
549
- options?: GeoSearchOptions,
550
- callback?: Callback<Array<ResultDoc>>
551
- ): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
552
-
553
- /** Executes a mapReduce command. */
554
- mapReduce<Key, Value>(
555
- o: MapReduceOptions<T, Key, Value>,
556
- callback?: Callback
557
- ): Promise<any>;
558
-
559
- remove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: any, callback?: CallbackWithoutResult): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
560
-
561
- /** Creates a `replaceOne` query: finds the first document that matches `filter` and replaces it with `replacement`. */
562
- replaceOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
563
- filter?: FilterQuery<T>,
564
- replacement?: T | AnyObject,
565
- options?: QueryOptions<T> | null,
566
- callback?: Callback
567
- ): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
568
- replaceOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
569
- filter?: FilterQuery<T>,
570
- replacement?: T | AnyObject,
571
- options?: QueryOptions<T> | null,
572
- callback?: Callback
573
- ): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
574
-
575
- /** Schema the model uses. */
576
- schema: Schema<T>;
577
-
578
- /**
579
- * @deprecated use `updateOne` or `updateMany` instead.
580
- * Creates a `update` query: updates one or many documents that match `filter` with `update`, based on the `multi` option.
581
- */
582
- update<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
583
- filter?: FilterQuery<T>,
584
- update?: UpdateQuery<T> | UpdateWithAggregationPipeline,
585
- options?: QueryOptions<T> | null,
586
- callback?: Callback
587
- ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
588
-
589
- /** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */
590
- updateMany<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
591
- filter?: FilterQuery<T>,
592
- update?: UpdateQuery<T> | UpdateWithAggregationPipeline,
593
- options?: QueryOptions<T> | null,
594
- callback?: Callback
595
- ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
596
-
597
- /** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */
598
- updateOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
599
- filter?: FilterQuery<T>,
600
- update?: UpdateQuery<T> | UpdateWithAggregationPipeline,
601
- options?: QueryOptions<T> | null,
602
- callback?: Callback
603
- ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
604
-
605
- /** Creates a Query, applies the passed conditions, and returns the Query. */
606
- where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(path: string, val?: any): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
607
- where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(obj: object): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
608
- where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
609
- }
610
-
611
- export type UpdateWriteOpResult = mongodb.UpdateResult;
612
-
613
- export interface QueryOptions<DocType = unknown> {
614
- arrayFilters?: { [key: string]: any }[];
615
- batchSize?: number;
616
- collation?: mongodb.CollationOptions;
617
- comment?: any;
618
- context?: string;
619
- explain?: any;
620
- fields?: any | string;
621
- hint?: any;
622
- /**
623
- * If truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document.
624
- */
625
- lean?: boolean | any;
626
- limit?: number;
627
- maxTimeMS?: number;
628
- maxscan?: number;
629
- multi?: boolean;
630
- multipleCastError?: boolean;
631
- /**
632
- * By default, `findOneAndUpdate()` returns the document as it was **before**
633
- * `update` was applied. If you set `new: true`, `findOneAndUpdate()` will
634
- * instead give you the object after `update` was applied.
635
- */
636
- new?: boolean;
637
- overwrite?: boolean;
638
- overwriteDiscriminatorKey?: boolean;
639
- populate?: string | string[] | PopulateOptions | PopulateOptions[];
640
- projection?: ProjectionType<DocType>;
641
- /**
642
- * if true, returns the raw result from the MongoDB driver
643
- */
644
- rawResult?: boolean;
645
- readPreference?: string | mongodb.ReadPreferenceMode;
646
- /**
647
- * An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`.
648
- */
649
- returnOriginal?: boolean;
650
- /**
651
- * Another alias for the `new` option. `returnOriginal` is deprecated so this should be used.
652
- */
653
- returnDocument?: string;
654
- runValidators?: boolean;
655
- /* Set to `true` to automatically sanitize potentially unsafe user-generated query projections */
656
- sanitizeProjection?: boolean;
657
- /**
658
- * Set to `true` to automatically sanitize potentially unsafe query filters by stripping out query selectors that
659
- * aren't explicitly allowed using `mongoose.trusted()`.
660
- */
661
- sanitizeFilter?: boolean;
662
- /** The session associated with this query. */
663
- session?: mongodb.ClientSession;
664
- setDefaultsOnInsert?: boolean;
665
- skip?: number;
666
- snapshot?: any;
667
- sort?: any;
668
- /** overwrites the schema's strict mode option */
669
- strict?: boolean | string;
670
- /**
671
- * equal to `strict` by default, may be `false`, `true`, or `'throw'`. Sets the default
672
- * [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery) mode for schemas.
673
- */
674
- strictQuery?: boolean | 'throw';
675
- tailable?: number;
676
- /**
677
- * If set to `false` and schema-level timestamps are enabled,
678
- * skip timestamps for this update. Note that this allows you to overwrite
679
- * timestamps. Does nothing if schema-level timestamps are not set.
680
- */
681
- timestamps?: boolean;
682
- upsert?: boolean;
683
- writeConcern?: any;
684
-
685
- [other: string]: any;
686
- }
687
-
688
- export type MongooseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, 'populate' | 'lean' | 'strict' | 'sanitizeProjection' | 'sanitizeFilter'>;
689
-
690
- export interface SaveOptions {
691
- checkKeys?: boolean;
692
- j?: boolean;
693
- safe?: boolean | WriteConcern;
694
- session?: ClientSession | null;
695
- timestamps?: boolean;
696
- validateBeforeSave?: boolean;
697
- validateModifiedOnly?: boolean;
698
- w?: number | string;
699
- wtimeout?: number;
700
- }
701
-
702
- export interface WriteConcern {
703
- j?: boolean;
704
- w?: number | 'majority' | TagSet;
705
- wtimeout?: number;
706
- }
707
-
708
98
  export interface TagSet {
709
99
  [k: string]: string;
710
100
  }
711
101
 
712
- export interface InsertManyOptions {
713
- limit?: number;
714
- rawResult?: boolean;
715
- ordered?: boolean;
716
- lean?: boolean;
717
- session?: mongodb.ClientSession;
718
- populate?: string | string[] | PopulateOptions | PopulateOptions[];
719
- }
720
-
721
- export type InferIdType<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
722
- export type InsertManyResult<T> = mongodb.InsertManyResult<T> & {
723
- insertedIds: {
724
- [key: number]: InferIdType<T>;
725
- };
726
- mongoose?: { validationErrors?: Array<Error.CastError | Error.ValidatorError> };
727
- };
728
-
729
- export interface MapReduceOptions<T, Key, Val> {
730
- map: Function | string;
731
- reduce: (key: Key, vals: T[]) => Val;
732
- /** query filter object. */
733
- query?: any;
734
- /** sort input objects using this key */
735
- sort?: any;
736
- /** max number of documents */
737
- limit?: number;
738
- /** keep temporary data default: false */
739
- keeptemp?: boolean;
740
- /** finalize function */
741
- finalize?: (key: Key, val: Val) => Val;
742
- /** scope variables exposed to map/reduce/finalize during execution */
743
- scope?: any;
744
- /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */
745
- jsMode?: boolean;
746
- /** provide statistics on job execution time. default: false */
747
- verbose?: boolean;
748
- readPreference?: string;
749
- /** sets the output target for the map reduce job. default: {inline: 1} */
750
- out?: {
751
- /** the results are returned in an array */
752
- inline?: number;
753
- /**
754
- * {replace: 'collectionName'} add the results to collectionName: the
755
- * results replace the collection
756
- */
757
- replace?: string;
758
- /**
759
- * {reduce: 'collectionName'} add the results to collectionName: if
760
- * dups are detected, uses the reducer / finalize functions
761
- */
762
- reduce?: string;
763
- /**
764
- * {merge: 'collectionName'} add the results to collectionName: if
765
- * dups exist the new docs overwrite the old
766
- */
767
- merge?: string;
768
- };
769
- }
770
-
771
- export interface GeoSearchOptions {
772
- /** x,y point to search for */
773
- near: number[];
774
- /** the maximum distance from the point near that a result can be */
775
- maxDistance: number;
776
- /** The maximum number of results to return */
777
- limit?: number;
778
- /** return the raw object instead of the Mongoose Model */
779
- lean?: boolean;
780
- }
781
-
782
- export interface PopulateOptions {
783
- /** space delimited path(s) to populate */
784
- path: string;
785
- /** fields to select */
786
- select?: any;
787
- /** query conditions to match */
788
- match?: any;
789
- /** optional model to use for population */
790
- model?: string | Model<any>;
791
- /** optional query options like sort, limit, etc */
792
- options?: any;
793
- /** correct limit on populated array */
794
- perDocumentLimit?: number;
795
- /** optional boolean, set to `false` to allow populating paths that aren't in the schema */
796
- strictPopulate?: boolean;
797
- /** deep populate */
798
- populate?: string | PopulateOptions | (string | PopulateOptions)[];
799
- /**
800
- * If true Mongoose will always set `path` to an array, if false Mongoose will
801
- * always set `path` to a document. Inferred from schema by default.
802
- */
803
- justOne?: boolean;
804
- /** transform function to call on every populated doc */
805
- transform?: (doc: any, id: any) => any;
806
- }
807
-
808
102
  export interface ToObjectOptions {
809
103
  /** apply all getters (path and virtual getters) */
810
104
  getters?: boolean;
@@ -826,21 +120,18 @@ declare module 'mongoose' {
826
120
  useProjection?: boolean;
827
121
  }
828
122
 
829
- export type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init';
830
- export type MongooseQueryMiddleware = 'count' | 'deleteMany' | 'deleteOne' | 'distinct' | 'find' | 'findOne' | 'findOneAndDelete' | 'findOneAndRemove' | 'findOneAndUpdate' | 'remove' | 'update' | 'updateOne' | 'updateMany';
123
+ export type DiscriminatorModel<M, T> = T extends Model<infer T1, infer T2, infer T3, infer T4>
124
+ ?
125
+ M extends Model<infer M1, infer M2, infer M3, infer M4>
126
+ ? Model<Omit<M1, keyof T1> & T1, M2 | T2, M3 | T3, M4 | T4>
127
+ : M
128
+ : M;
831
129
 
832
- export type SchemaPreOptions = { document?: boolean, query?: boolean };
833
- export type SchemaPostOptions = { document?: boolean, query?: boolean };
130
+ export type DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, T> = T extends Schema<infer T1, infer T2, infer T3, infer T4, infer T5>
131
+ ? Schema<Omit<DocType, keyof T1> & T1, DiscriminatorModel<T2, M>, T3 | TInstanceMethods, T4 | TQueryHelpers, T5 | TVirtuals>
132
+ : Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals>;
834
133
 
835
- export type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
836
- export type IndexDefinition = Record<string, IndexDirection>;
837
-
838
- export type PreMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
839
- export type PreSaveMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError, opts: SaveOptions) => void | Promise<void>;
840
- export type PostMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
841
- export type ErrorHandlingMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void;
842
-
843
- export class Schema<DocType = any, M = Model<DocType, any, any, any>, TInstanceMethods = {}, TQueryHelpers = {}> extends events.EventEmitter {
134
+ export class Schema<DocType = any, M = Model<DocType, any, any, any>, TInstanceMethods = {}, TQueryHelpers = {}, TVirtuals = any> extends events.EventEmitter {
844
135
  /**
845
136
  * Create a new schema
846
137
  */
@@ -862,6 +153,8 @@ declare module 'mongoose' {
862
153
  /** Returns a copy of this schema */
863
154
  clone<T = this>(): T;
864
155
 
156
+ discriminator<T extends Schema = Schema>(name: string, schema: T): DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, T>;
157
+
865
158
  /** Returns a new schema that has the picked `paths` from this schema. */
866
159
  pick<T = this>(paths: string[], options?: SchemaOptions): T;
867
160
 
@@ -981,7 +274,7 @@ declare module 'mongoose' {
981
274
  ): VirtualType<T>;
982
275
 
983
276
  /** Object of currently defined virtuals on this schema */
984
- virtuals: any;
277
+ virtuals: TVirtuals;
985
278
 
986
279
  /** Returns the virtual type with the given `name`. */
987
280
  virtualpath<T = HydratedDocument<DocType, TInstanceMethods>>(name: string): VirtualType<T> | null;
@@ -1019,161 +312,13 @@ declare module 'mongoose' {
1019
312
  ? { [path: string]: SchemaDefinitionProperty; }
1020
313
  : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
1021
314
 
1022
- export type Unpacked<T> = T extends (infer U)[] ?
1023
- U :
1024
- T extends ReadonlyArray<infer U> ? U : T;
1025
-
1026
315
  export type AnyArray<T> = T[] | ReadonlyArray<T>;
1027
- export type SchemaValidator<T> = RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
1028
-
1029
316
  export type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
1030
317
 
1031
318
  export interface MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
1032
319
  type: typeof Schema.Types.Mixed;
1033
320
  }
1034
321
 
1035
- export interface SchemaTypeOptions<T> {
1036
- type?:
1037
- T extends string ? StringSchemaDefinition :
1038
- T extends number ? NumberSchemaDefinition :
1039
- T extends boolean ? BooleanSchemaDefinition :
1040
- T extends NativeDate ? DateSchemaDefinition :
1041
- T extends Map<any, any> ? SchemaDefinition<typeof Map> :
1042
- T extends Buffer ? SchemaDefinition<typeof Buffer> :
1043
- T extends Types.ObjectId ? ObjectIdSchemaDefinition :
1044
- T extends Types.ObjectId[] ? AnyArray<ObjectIdSchemaDefinition> | AnyArray<SchemaTypeOptions<ObjectId>> :
1045
- T extends object[] ? (AnyArray<Schema<any, any, any>> | AnyArray<SchemaDefinition<Unpacked<T>>> | AnyArray<SchemaTypeOptions<Unpacked<T>>>) :
1046
- T extends string[] ? AnyArray<StringSchemaDefinition> | AnyArray<SchemaTypeOptions<string>> :
1047
- T extends number[] ? AnyArray<NumberSchemaDefinition> | AnyArray<SchemaTypeOptions<number>> :
1048
- T extends boolean[] ? AnyArray<BooleanSchemaDefinition> | AnyArray<SchemaTypeOptions<boolean>> :
1049
- T extends Function[] ? AnyArray<Function | string> | AnyArray<SchemaTypeOptions<Unpacked<T>>> :
1050
- T | typeof SchemaType | Schema<any, any, any> | SchemaDefinition<T> | Function | AnyArray<Function>;
1051
-
1052
- /** Defines a virtual with the given name that gets/sets this path. */
1053
- alias?: string;
1054
-
1055
- /** Function or object describing how to validate this schematype. See [validation docs](https://mongoosejs.com/docs/validation.html). */
1056
- validate?: SchemaValidator<T> | AnyArray<SchemaValidator<T>>;
1057
-
1058
- /** Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message. */
1059
- cast?: string;
1060
-
1061
- /**
1062
- * If true, attach a required validator to this path, which ensures this path
1063
- * path cannot be set to a nullish value. If a function, Mongoose calls the
1064
- * function and only checks for nullish values if the function returns a truthy value.
1065
- */
1066
- required?: boolean | (() => boolean) | [boolean, string] | [() => boolean, string];
1067
-
1068
- /**
1069
- * The default value for this path. If a function, Mongoose executes the function
1070
- * and uses the return value as the default.
1071
- */
1072
- default?: T extends Schema.Types.Mixed ? ({} | ((this: any, doc: any) => any)) : (ExtractMongooseArray<T> | ((this: any, doc: any) => Partial<ExtractMongooseArray<T>>));
1073
-
1074
- /**
1075
- * The model that `populate()` should use if populating this path.
1076
- */
1077
- ref?: string | Model<any> | ((this: any, doc: any) => string | Model<any>);
1078
-
1079
- /**
1080
- * Whether to include or exclude this path by default when loading documents
1081
- * using `find()`, `findOne()`, etc.
1082
- */
1083
- select?: boolean | number;
1084
-
1085
- /**
1086
- * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
1087
- * build an index on this path when the model is compiled.
1088
- */
1089
- index?: boolean | number | IndexOptions | '2d' | '2dsphere' | 'hashed' | 'text';
1090
-
1091
- /**
1092
- * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose
1093
- * will build a unique index on this path when the
1094
- * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator).
1095
- */
1096
- unique?: boolean | number;
1097
-
1098
- /**
1099
- * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
1100
- * disallow changes to this path once the document is saved to the database for the first time. Read more
1101
- * about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html).
1102
- */
1103
- immutable?: boolean | ((this: any, doc: any) => boolean);
1104
-
1105
- /**
1106
- * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
1107
- * build a sparse index on this path.
1108
- */
1109
- sparse?: boolean | number;
1110
-
1111
- /**
1112
- * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose
1113
- * will build a text index on this path.
1114
- */
1115
- text?: boolean | number | any;
1116
-
1117
- /**
1118
- * Define a transform function for this individual schema type.
1119
- * Only called when calling `toJSON()` or `toObject()`.
1120
- */
1121
- transform?: (this: any, val: T) => any;
1122
-
1123
- /** defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
1124
- get?: (value: any, doc?: this) => T;
1125
-
1126
- /** defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
1127
- set?: (value: any, priorVal?: T, doc?: this) => any;
1128
-
1129
- /** array of allowed values for this path. Allowed for strings, numbers, and arrays of strings */
1130
- enum?: Array<string | number | null> | ReadonlyArray<string | number | null> | { values: Array<string | number | null> | ReadonlyArray<string | number | null>, message?: string } | { [path: string]: string | number | null };
1131
-
1132
- /** The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths */
1133
- subtype?: number;
1134
-
1135
- /** The minimum value allowed for this path. Only allowed for numbers and dates. */
1136
- min?: number | NativeDate | [number, string] | [NativeDate, string] | readonly [number, string] | readonly [NativeDate, string];
1137
-
1138
- /** The maximum value allowed for this path. Only allowed for numbers and dates. */
1139
- max?: number | NativeDate | [number, string] | [NativeDate, string] | readonly [number, string] | readonly [NativeDate, string];
1140
-
1141
- /** Defines a TTL index on this path. Only allowed for dates. */
1142
- expires?: string | number;
1143
-
1144
- /** If `true`, Mongoose will skip gathering indexes on subpaths. Only allowed for subdocuments and subdocument arrays. */
1145
- excludeIndexes?: boolean;
1146
-
1147
- /** If set, overrides the child schema's `_id` option. Only allowed for subdocuments and subdocument arrays. */
1148
- _id?: boolean;
1149
-
1150
- /** If set, specifies the type of this map's values. Mongoose will cast this map's values to the given type. */
1151
- of?: Function | SchemaDefinitionProperty<any>;
1152
-
1153
- /** If true, uses Mongoose's default `_id` settings. Only allowed for ObjectIds */
1154
- auto?: boolean;
1155
-
1156
- /** Attaches a validator that succeeds if the data string matches the given regular expression, and fails otherwise. */
1157
- match?: RegExp | [RegExp, string] | readonly [RegExp, string];
1158
-
1159
- /** If truthy, Mongoose will add a custom setter that lowercases this string using JavaScript's built-in `String#toLowerCase()`. */
1160
- lowercase?: boolean;
1161
-
1162
- /** If truthy, Mongoose will add a custom setter that removes leading and trailing whitespace using JavaScript's built-in `String#trim()`. */
1163
- trim?: boolean;
1164
-
1165
- /** If truthy, Mongoose will add a custom setter that uppercases this string using JavaScript's built-in `String#toUpperCase()`. */
1166
- uppercase?: boolean;
1167
-
1168
- /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at least the given number. */
1169
- minlength?: number | [number, string] | readonly [number, string];
1170
-
1171
- /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at most the given number. */
1172
- maxlength?: number | [number, string] | readonly [number, string];
1173
-
1174
- [other: string]: any;
1175
- }
1176
-
1177
322
  export type RefType =
1178
323
  | number
1179
324
  | string
@@ -1186,66 +331,6 @@ declare module 'mongoose' {
1186
331
  | typeof Schema.Types.Buffer
1187
332
  | typeof Schema.Types.ObjectId;
1188
333
 
1189
- /**
1190
- * Reference another Model
1191
- */
1192
- export type PopulatedDoc<
1193
- PopulatedType,
1194
- RawId extends RefType = (PopulatedType extends { _id?: RefType; } ? NonNullable<PopulatedType['_id']> : Types.ObjectId) | undefined
1195
- > = PopulatedType | RawId;
1196
-
1197
- export interface IndexOptions extends mongodb.CreateIndexesOptions {
1198
- /**
1199
- * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
1200
- *
1201
- * @example
1202
- * ```js
1203
- * const schema = new Schema({ prop1: Date });
1204
- *
1205
- * // expire in 24 hours
1206
- * schema.index({ prop1: 1 }, { expires: 60*60*24 })
1207
- *
1208
- * // expire in 24 hours
1209
- * schema.index({ prop1: 1 }, { expires: '24h' })
1210
- *
1211
- * // expire in 1.5 hours
1212
- * schema.index({ prop1: 1 }, { expires: '1.5h' })
1213
- *
1214
- * // expire in 7 days
1215
- * schema.index({ prop1: 1 }, { expires: '7d' })
1216
- * ```
1217
- */
1218
- expires?: number | string;
1219
- weights?: AnyObject;
1220
- }
1221
-
1222
- export interface ValidatorProps {
1223
- path: string;
1224
- value: any;
1225
- }
1226
-
1227
- export interface ValidatorMessageFn {
1228
- (props: ValidatorProps): string;
1229
- }
1230
-
1231
- export interface ValidateFn<T> {
1232
- (value: T): boolean;
1233
- }
1234
-
1235
- export interface LegacyAsyncValidateFn<T> {
1236
- (value: T, done: (result: boolean) => void): void;
1237
- }
1238
-
1239
- export interface AsyncValidateFn<T> {
1240
- (value: any): Promise<boolean>;
1241
- }
1242
-
1243
- export interface ValidateOpts<T> {
1244
- msg?: string;
1245
- message?: string | ValidatorMessageFn;
1246
- type?: string;
1247
- validator: ValidateFn<T> | LegacyAsyncValidateFn<T> | AsyncValidateFn<T>;
1248
- }
1249
334
 
1250
335
  export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1251
336
 
@@ -1313,827 +398,14 @@ declare module 'mongoose' {
1313
398
  set<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => void): this;
1314
399
  }
1315
400
 
1316
- export namespace Schema {
1317
- namespace Types {
1318
- class Array extends SchemaType implements AcceptsDiscriminator {
1319
- /** This schema type's name, to defend against minifiers that mangle function names. */
1320
- static schemaName: string;
1321
-
1322
- static options: { castNonArrays: boolean; };
1323
-
1324
- discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
1325
- discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
1326
-
1327
- /** The schematype embedded in this array */
1328
- caster?: SchemaType;
1329
-
1330
- /**
1331
- * Adds an enum validator if this is an array of strings or numbers. Equivalent to
1332
- * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()`
1333
- */
1334
- enum(vals: string[] | number[]): this;
1335
- }
1336
-
1337
- class Boolean extends SchemaType {
1338
- /** This schema type's name, to defend against minifiers that mangle function names. */
1339
- static schemaName: string;
1340
-
1341
- /** Configure which values get casted to `true`. */
1342
- static convertToTrue: Set<any>;
1343
-
1344
- /** Configure which values get casted to `false`. */
1345
- static convertToFalse: Set<any>;
1346
- }
1347
-
1348
- class Buffer extends SchemaType {
1349
- /** This schema type's name, to defend against minifiers that mangle function names. */
1350
- static schemaName: string;
1351
-
1352
- /**
1353
- * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/)
1354
- * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html).
1355
- */
1356
- subtype(subtype: number): this;
1357
- }
1358
-
1359
- class Date extends SchemaType {
1360
- /** This schema type's name, to defend against minifiers that mangle function names. */
1361
- static schemaName: string;
1362
-
1363
- /** Declares a TTL index (rounded to the nearest second) for _Date_ types only. */
1364
- expires(when: number | string): this;
1365
-
1366
- /** Sets a maximum date validator. */
1367
- max(value: NativeDate, message: string): this;
1368
-
1369
- /** Sets a minimum date validator. */
1370
- min(value: NativeDate, message: string): this;
1371
- }
1372
-
1373
- class Decimal128 extends SchemaType {
1374
- /** This schema type's name, to defend against minifiers that mangle function names. */
1375
- static schemaName: string;
1376
- }
1377
-
1378
- class DocumentArray extends SchemaType implements AcceptsDiscriminator {
1379
- /** This schema type's name, to defend against minifiers that mangle function names. */
1380
- static schemaName: string;
1381
-
1382
- static options: { castNonArrays: boolean; };
1383
-
1384
- discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
1385
- discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
1386
-
1387
- /** The schema used for documents in this array */
1388
- schema: Schema;
1389
-
1390
- /** The constructor used for subdocuments in this array */
1391
- caster?: typeof Types.Subdocument;
1392
- }
1393
-
1394
- class Map extends SchemaType {
1395
- /** This schema type's name, to defend against minifiers that mangle function names. */
1396
- static schemaName: string;
1397
- }
1398
-
1399
- class Mixed extends SchemaType {
1400
- /** This schema type's name, to defend against minifiers that mangle function names. */
1401
- static schemaName: string;
1402
- }
1403
-
1404
- class Number extends SchemaType {
1405
- /** This schema type's name, to defend against minifiers that mangle function names. */
1406
- static schemaName: string;
1407
-
1408
- /** Sets a enum validator */
1409
- enum(vals: number[]): this;
1410
-
1411
- /** Sets a maximum number validator. */
1412
- max(value: number, message: string): this;
1413
-
1414
- /** Sets a minimum number validator. */
1415
- min(value: number, message: string): this;
1416
- }
1417
-
1418
- class ObjectId extends SchemaType {
1419
- /** This schema type's name, to defend against minifiers that mangle function names. */
1420
- static schemaName: string;
1421
-
1422
- /** Adds an auto-generated ObjectId default if turnOn is true. */
1423
- auto(turnOn: boolean): this;
1424
- }
1425
-
1426
- class Subdocument extends SchemaType implements AcceptsDiscriminator {
1427
- /** This schema type's name, to defend against minifiers that mangle function names. */
1428
- static schemaName: string;
1429
-
1430
- /** The document's schema */
1431
- schema: Schema;
1432
-
1433
- discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
1434
- discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
1435
- }
1436
-
1437
- class String extends SchemaType {
1438
- /** This schema type's name, to defend against minifiers that mangle function names. */
1439
- static schemaName: string;
1440
-
1441
- /** Adds an enum validator */
1442
- enum(vals: string[] | any): this;
1443
-
1444
- /** Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
1445
- lowercase(shouldApply?: boolean): this;
1446
-
1447
- /** Sets a regexp validator. */
1448
- match(value: RegExp, message: string): this;
1449
-
1450
- /** Sets a maximum length validator. */
1451
- maxlength(value: number, message: string): this;
1452
-
1453
- /** Sets a minimum length validator. */
1454
- minlength(value: number, message: string): this;
1455
-
1456
- /** Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
1457
- trim(shouldTrim?: boolean): this;
1458
-
1459
- /** Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). */
1460
- uppercase(shouldApply?: boolean): this;
1461
- }
1462
- }
1463
- }
1464
-
1465
- export namespace Types {
1466
- class Array<T> extends global.Array<T> {
1467
- /** Pops the array atomically at most one time per document `save()`. */
1468
- $pop(): T;
1469
-
1470
- /** Atomically shifts the array at most one time per document `save()`. */
1471
- $shift(): T;
1472
-
1473
- /** Adds values to the array if not already present. */
1474
- addToSet(...args: any[]): any[];
1475
-
1476
- isMongooseArray: true;
1477
-
1478
- /** Pushes items to the array non-atomically. */
1479
- nonAtomicPush(...args: any[]): number;
1480
-
1481
- /** Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. */
1482
- push(...args: any[]): number;
1483
-
1484
- /**
1485
- * Pulls items from the array atomically. Equality is determined by casting
1486
- * the provided value to an embedded document and comparing using
1487
- * [the `Document.equals()` function.](./api.html#document_Document-equals)
1488
- */
1489
- pull(...args: any[]): this;
1490
-
1491
- /**
1492
- * Alias of [pull](#mongoosearray_MongooseArray-pull)
1493
- */
1494
- remove(...args: any[]): this;
1495
-
1496
- /** Sets the casted `val` at index `i` and marks the array modified. */
1497
- set(i: number, val: T): this;
1498
-
1499
- /** Atomically shifts the array at most one time per document `save()`. */
1500
- shift(): T;
1501
-
1502
- /** Returns a native js Array. */
1503
- toObject(options?: ToObjectOptions): any;
1504
- toObject<T>(options?: ToObjectOptions): T;
1505
-
1506
- /** Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. */
1507
- unshift(...args: any[]): number;
1508
- }
1509
-
1510
- class Buffer extends global.Buffer {
1511
- /** Sets the subtype option and marks the buffer modified. */
1512
- subtype(subtype: number | ToObjectOptions): void;
1513
-
1514
- /** Converts this buffer to its Binary type representation. */
1515
- toObject(subtype?: number): mongodb.Binary;
1516
- }
1517
-
1518
- class Decimal128 extends mongodb.Decimal128 { }
1519
-
1520
- class DocumentArray<T> extends Types.Array<T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T> {
1521
- /** DocumentArray constructor */
1522
- constructor(values: any[]);
1523
-
1524
- isMongooseDocumentArray: true;
1525
-
1526
- /** Creates a subdocument casted to this schema. */
1527
- create(obj: any): T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T;
1528
-
1529
- /** Searches array items for the first document with a matching _id. */
1530
- id(id: any): (T extends Types.Subdocument ? T : Types.Subdocument<InferId<T>> & T) | null;
1531
-
1532
- push(...args: (AnyKeys<T> & AnyObject)[]): number;
1533
- }
1534
-
1535
- class Map<V> extends global.Map<string, V> {
1536
- /** Converts a Mongoose map into a vanilla JavaScript map. */
1537
- toObject(options?: ToObjectOptions & { flattenMaps?: boolean }): any;
1538
- }
1539
-
1540
- class ObjectId extends mongodb.ObjectId {
1541
- _id: this;
1542
- }
1543
-
1544
- class Subdocument<IdType = any> extends Document<IdType> {
1545
- $isSingleNested: true;
1546
-
1547
- /** Returns the top level document of this sub-document. */
1548
- ownerDocument(): Document;
1549
-
1550
- /** Returns this sub-documents parent document. */
1551
- parent(): Document;
1552
-
1553
- /** Returns this sub-documents parent document. */
1554
- $parent(): Document;
1555
- }
1556
-
1557
- class ArraySubdocument<IdType = any> extends Subdocument<IdType> {
1558
- /** Returns this sub-documents parent array. */
1559
- parentArray(): Types.DocumentArray<unknown>;
1560
- }
1561
- }
1562
-
1563
401
  export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1564
402
 
1565
- export type QueryWithHelpers<ResultType, DocType, THelpers = {}, RawDocType = DocType> = Query<ResultType, DocType, THelpers, RawDocType> & THelpers;
1566
-
1567
- export type UnpackedIntersection<T, U> = T extends null ? null : T extends (infer A)[]
1568
- ? (Omit<A, keyof U> & U)[]
1569
- : keyof U extends never
1570
- ? T
1571
- : Omit<T, keyof U> & U;
1572
-
1573
- export type ProjectionFields<DocType> = { [Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any } & Record<string, any>;
1574
-
1575
- export class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1576
- _mongooseOptions: MongooseQueryOptions<DocType>;
1577
-
1578
- /**
1579
- * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
1580
- * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
1581
- * This is equivalent to calling `.cursor()` with no arguments.
1582
- */
1583
- [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
1584
-
1585
- /** Executes the query */
1586
- exec(): Promise<ResultType>;
1587
- exec(callback?: Callback<ResultType>): void;
1588
- // @todo: this doesn't seem right
1589
- exec(callback?: Callback<ResultType>): Promise<ResultType> | any;
1590
-
1591
- $where(argument: string | Function): QueryWithHelpers<DocType[], DocType, THelpers, RawDocType>;
1592
-
1593
- /** Specifies an `$all` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1594
- all(val: Array<any>): this;
1595
- all(path: string, val: Array<any>): this;
1596
-
1597
- /** Sets the allowDiskUse option for the query (ignored for < 4.4.0) */
1598
- allowDiskUse(value: boolean): this;
1599
-
1600
- /** Specifies arguments for an `$and` condition. */
1601
- and(array: FilterQuery<DocType>[]): this;
1602
-
1603
- /** Specifies the batchSize option. */
1604
- batchSize(val: number): this;
1605
-
1606
- /** Specifies a `$box` condition */
1607
- box(val: any): this;
1608
- box(lower: number[], upper: number[]): this;
1609
-
1610
- /**
1611
- * Casts this query to the schema of `model`.
1612
- *
1613
- * @param {Model} [model] the model to cast to. If not set, defaults to `this.model`
1614
- * @param {Object} [obj] If not set, defaults to this query's conditions
1615
- * @return {Object} the casted `obj`
1616
- */
1617
- cast(model?: Model<any, THelpers> | null, obj?: any): any;
1618
-
1619
- /**
1620
- * Executes the query returning a `Promise` which will be
1621
- * resolved with either the doc(s) or rejected with the error.
1622
- * Like `.then()`, but only takes a rejection handler.
1623
- */
1624
- catch: Promise<ResultType>['catch'];
1625
-
1626
- /** Specifies a `$center` or `$centerSphere` condition. */
1627
- circle(area: any): this;
1628
- circle(path: string, area: any): this;
1629
-
1630
- /** Make a copy of this query so you can re-execute it. */
1631
- clone(): this;
1632
-
1633
- /** Adds a collation to this op (MongoDB 3.4 and up) */
1634
- collation(value: mongodb.CollationOptions): this;
1635
-
1636
- /** Specifies the `comment` option. */
1637
- comment(val: string): this;
1638
-
1639
- /** Specifies this query as a `count` query. */
1640
- count(callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1641
- count(criteria: FilterQuery<DocType>, callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1642
-
1643
- /** Specifies this query as a `countDocuments` query. */
1644
- countDocuments(callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1645
- countDocuments(
1646
- criteria: FilterQuery<DocType>,
1647
- options?: QueryOptions<DocType>,
1648
- callback?: Callback<number>
1649
- ): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1650
-
1651
- /**
1652
- * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
1653
- * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
1654
- */
1655
- cursor(options?: QueryOptions<DocType>): Cursor<DocType, QueryOptions<DocType>>;
1656
-
1657
- /**
1658
- * Declare and/or execute this query as a `deleteMany()` operation. Works like
1659
- * remove, except it deletes _every_ document that matches `filter` in the
1660
- * collection, regardless of the value of `single`.
1661
- */
1662
- deleteMany(filter?: FilterQuery<DocType>, options?: QueryOptions<DocType>, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1663
- deleteMany(filter: FilterQuery<DocType>, callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1664
- deleteMany(callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1665
-
1666
- /**
1667
- * Declare and/or execute this query as a `deleteOne()` operation. Works like
1668
- * remove, except it deletes at most one document regardless of the `single`
1669
- * option.
1670
- */
1671
- deleteOne(filter?: FilterQuery<DocType>, options?: QueryOptions<DocType>, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1672
- deleteOne(filter: FilterQuery<DocType>, callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1673
- deleteOne(callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1674
-
1675
- /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
1676
- distinct<ReturnType = any>(field: string, filter?: FilterQuery<DocType>, callback?: Callback<number>): QueryWithHelpers<Array<ReturnType>, DocType, THelpers, RawDocType>;
1677
-
1678
- /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1679
- elemMatch(val: Function | any): this;
1680
- elemMatch<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$elemMatch']): this;
1681
-
1682
- /**
1683
- * Gets/sets the error flag on this query. If this flag is not null or
1684
- * undefined, the `exec()` promise will reject without executing.
1685
- */
1686
- error(): NativeError | null;
1687
- error(val: NativeError | null): this;
1688
-
1689
- /** Specifies the complementary comparison value for paths specified with `where()` */
1690
- equals(val: any): this;
1691
-
1692
- /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
1693
- estimatedDocumentCount(options?: QueryOptions<DocType>, callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1694
-
1695
- /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1696
- exists(val: boolean): this;
1697
- exists<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$exists']): this;
1698
-
1699
- /**
1700
- * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
1701
- * which makes this query return detailed execution stats instead of the actual
1702
- * query result. This method is useful for determining what index your queries
1703
- * use.
1704
- */
1705
- explain(verbose?: string): this;
1706
-
1707
- /** Creates a `find` query: gets a list of documents that match `filter`. */
1708
- find(callback?: Callback<DocType[]>): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1709
- find(
1710
- filter: FilterQuery<DocType>,
1711
- callback?: Callback<DocType[]>
1712
- ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1713
- find(
1714
- filter: FilterQuery<DocType>,
1715
- projection?: ProjectionType<DocType> | null,
1716
- callback?: Callback<DocType[]>
1717
- ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1718
- find(
1719
- filter: FilterQuery<DocType>,
1720
- projection?: ProjectionType<DocType> | null,
1721
- options?: QueryOptions<DocType> | null,
1722
- callback?: Callback<DocType[]>
1723
- ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1724
-
1725
- /** Declares the query a findOne operation. When executed, the first found document is passed to the callback. */
1726
- findOne(
1727
- filter?: FilterQuery<DocType>,
1728
- projection?: ProjectionType<DocType> | null,
1729
- options?: QueryOptions<DocType> | null,
1730
- callback?: Callback<DocType | null>
1731
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1732
- findOne(
1733
- filter?: FilterQuery<DocType>,
1734
- projection?: ProjectionType<DocType> | null,
1735
- callback?: Callback<DocType | null>
1736
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1737
- findOne(
1738
- filter?: FilterQuery<DocType>,
1739
- callback?: Callback<DocType | null>
1740
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1741
-
1742
- /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
1743
- findOneAndDelete(
1744
- filter?: FilterQuery<DocType>,
1745
- options?: QueryOptions<DocType> | null,
1746
- callback?: (err: CallbackError, doc: DocType | null, res: any) => void
1747
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1748
-
1749
- /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
1750
- findOneAndRemove(
1751
- filter?: FilterQuery<DocType>,
1752
- options?: QueryOptions<DocType> | null,
1753
- callback?: (err: CallbackError, doc: DocType | null, res: any) => void
1754
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1755
-
1756
- /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
1757
- findOneAndUpdate(
1758
- filter: FilterQuery<DocType>,
1759
- update: UpdateQuery<DocType>,
1760
- options: QueryOptions<DocType> & { rawResult: true },
1761
- callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
1762
- ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType>;
1763
- findOneAndUpdate(
1764
- filter: FilterQuery<DocType>,
1765
- update: UpdateQuery<DocType>,
1766
- options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc,
1767
- callback?: (err: CallbackError, doc: DocType, res: ModifyResult<DocType>) => void
1768
- ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
1769
- findOneAndUpdate(
1770
- filter?: FilterQuery<DocType>,
1771
- update?: UpdateQuery<DocType>,
1772
- options?: QueryOptions<DocType> | null,
1773
- callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
1774
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1775
-
1776
- /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
1777
- findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions<DocType> | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1778
-
1779
- /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
1780
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, options: QueryOptions<DocType> & { rawResult: true }, callback?: (err: CallbackError, doc: any, res?: any) => void): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1781
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: DocType, res?: any) => void): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
1782
- findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery<DocType>, options?: QueryOptions<DocType> | null, callback?: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1783
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, callback: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1784
-
1785
- /** Specifies a `$geometry` condition */
1786
- geometry(object: { type: string, coordinates: any[] }): this;
1787
-
1788
- /**
1789
- * For update operations, returns the value of a path in the update's `$set`.
1790
- * Useful for writing getters/setters that can work with both update operations
1791
- * and `save()`.
1792
- */
1793
- get(path: string): any;
1794
-
1795
- /** Returns the current query filter (also known as conditions) as a POJO. */
1796
- getFilter(): FilterQuery<DocType>;
1797
-
1798
- /** Gets query options. */
1799
- getOptions(): QueryOptions<DocType>;
1800
-
1801
- /** Gets a list of paths to be populated by this query */
1802
- getPopulatedPaths(): Array<string>;
1803
-
1804
- /** Returns the current query filter. Equivalent to `getFilter()`. */
1805
- getQuery(): FilterQuery<DocType>;
1806
-
1807
- /** Returns the current update operations as a JSON object. */
1808
- getUpdate(): UpdateQuery<DocType> | UpdateWithAggregationPipeline | null;
1809
-
1810
- /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1811
- gt(val: number): this;
1812
- gt<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gt']): this;
1813
-
1814
- /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1815
- gte(val: number): this;
1816
- gte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gte']): this;
1817
-
1818
- /** Sets query hints. */
1819
- hint(val: any): this;
1820
-
1821
- /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1822
- in(val: Array<any>): this;
1823
- in<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$in']): this;
1824
-
1825
- /** Declares an intersects query for `geometry()`. */
1826
- intersects(arg?: any): this;
1827
-
1828
- /** Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. */
1829
- j(val: boolean | null): this;
1830
-
1831
- /** Sets the lean option. */
1832
- lean<LeanResultType = RawDocType extends Document ? LeanDocumentOrArray<ResultType> : LeanDocumentOrArrayWithRawType<ResultType, Require_id<RawDocType>>>(val?: boolean | any): QueryWithHelpers<LeanResultType, DocType, THelpers, RawDocType>;
1833
-
1834
- /** Specifies the maximum number of documents the query will return. */
1835
- limit(val: number): this;
1836
-
1837
- /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1838
- lt(val: number): this;
1839
- lt<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lt']): this;
1840
-
1841
- /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1842
- lte(val: number): this;
1843
- lte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lte']): this;
1844
-
1845
- /**
1846
- * Runs a function `fn` and treats the return value of `fn` as the new value
1847
- * for the query to resolve to.
1848
- */
1849
- transform<MappedType>(fn: (doc: ResultType) => MappedType): QueryWithHelpers<MappedType, DocType, THelpers, RawDocType>;
1850
-
1851
- /** Specifies an `$maxDistance` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1852
- maxDistance(val: number): this;
1853
- maxDistance(path: string, val: number): this;
1854
-
1855
- /** Specifies the maxScan option. */
1856
- maxScan(val: number): this;
1857
-
1858
- /**
1859
- * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/)
1860
- * option. This will tell the MongoDB server to abort if the query or write op
1861
- * has been running for more than `ms` milliseconds.
1862
- */
1863
- maxTimeMS(ms: number): this;
1864
-
1865
- /** Merges another Query or conditions object into this one. */
1866
- merge(source: Query<any, any> | FilterQuery<DocType>): this;
1867
-
1868
- /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
1869
- mod(val: Array<number>): this;
1870
- mod<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$mod']): this;
1871
-
1872
- /** The model this query was created from */
1873
- model: typeof Model;
1874
-
1875
- /**
1876
- * Getter/setter around the current mongoose-specific options for this query
1877
- * Below are the current Mongoose-specific options.
1878
- */
1879
- mongooseOptions(val?: MongooseQueryOptions): MongooseQueryOptions;
1880
-
1881
- /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1882
- ne(val: any): this;
1883
- ne<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$ne']): this;
1884
-
1885
- /** Specifies a `$near` or `$nearSphere` condition */
1886
- near(val: any): this;
1887
- near<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$near']): this;
1888
-
1889
- /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1890
- nin(val: Array<any>): this;
1891
- nin<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$nin']): this;
1892
-
1893
- /** Specifies arguments for an `$nor` condition. */
1894
- nor(array: Array<FilterQuery<DocType>>): this;
1895
-
1896
- /** Specifies arguments for an `$or` condition. */
1897
- or(array: Array<FilterQuery<DocType>>): this;
1898
-
1899
- /**
1900
- * Make this query throw an error if no documents match the given `filter`.
1901
- * This is handy for integrating with async/await, because `orFail()` saves you
1902
- * an extra `if` statement to check if no document was found.
1903
- */
1904
- orFail(err?: NativeError | (() => NativeError)): QueryWithHelpers<NonNullable<ResultType>, DocType, THelpers, RawDocType>;
1905
-
1906
- /** Specifies a `$polygon` condition */
1907
- polygon(...coordinatePairs: number[][]): this;
1908
- polygon(path: string, ...coordinatePairs: number[][]): this;
1909
-
1910
- /** Specifies paths which should be populated with other documents. */
1911
- populate<Paths = {}>(path: string | string[], select?: string | any, model?: string | Model<any, THelpers>, match?: any): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, UnpackedIntersection<RawDocType, Paths>>;
1912
- populate<Paths = {}>(options: PopulateOptions | (PopulateOptions | string)[]): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, UnpackedIntersection<RawDocType, Paths>>;
1913
-
1914
- /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */
1915
- projection(): ProjectionFields<DocType> | null;
1916
- projection(fields: null): null;
1917
- projection(fields?: ProjectionFields<DocType> | string): ProjectionFields<DocType>;
1918
-
1919
- /** Determines the MongoDB nodes from which to read. */
1920
- read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
1921
-
1922
- /** Sets the readConcern option for the query. */
1923
- readConcern(level: string): this;
1924
-
1925
- /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1926
- regex(val: string | RegExp): this;
1927
- regex<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$regex']): this;
1928
-
1929
- /**
1930
- * Declare and/or execute this query as a remove() operation. `remove()` is
1931
- * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne)
1932
- * or [`deleteMany()`](#query_Query-deleteMany) instead.
1933
- */
1934
- remove(filter?: FilterQuery<DocType>, callback?: Callback<mongodb.UpdateResult>): Query<mongodb.UpdateResult, DocType, THelpers, RawDocType>;
1935
-
1936
- /**
1937
- * Declare and/or execute this query as a replaceOne() operation. Same as
1938
- * `update()`, except MongoDB will replace the existing document and will
1939
- * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
1940
- */
1941
- replaceOne(filter?: FilterQuery<DocType>, replacement?: DocType | AnyObject, options?: QueryOptions<DocType> | null, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1942
- replaceOne(filter?: FilterQuery<DocType>, replacement?: DocType | AnyObject, options?: QueryOptions<DocType> | null, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1943
-
1944
- /** Specifies which document fields to include or exclude (also known as the query "projection") */
1945
- select(arg: string | any): this;
1946
-
1947
- /** Determines if field selection has been made. */
1948
- selected(): boolean;
1949
-
1950
- /** Determines if exclusive field selection has been made. */
1951
- selectedExclusively(): boolean;
1952
-
1953
- /** Determines if inclusive field selection has been made. */
1954
- selectedInclusively(): boolean;
1955
-
1956
- /**
1957
- * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/)
1958
- * associated with this query. Sessions are how you mark a query as part of a
1959
- * [transaction](/docs/transactions.html).
1960
- */
1961
- session(session: mongodb.ClientSession | null): this;
1962
-
1963
- /**
1964
- * Adds a `$set` to this query's update without changing the operation.
1965
- * This is useful for query middleware so you can add an update regardless
1966
- * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc.
1967
- */
1968
- set(path: string | Record<string, unknown>, value?: any): this;
1969
-
1970
- /** Sets query options. Some options only make sense for certain operations. */
1971
- setOptions(options: QueryOptions<DocType>, overwrite?: boolean): this;
1972
-
1973
- /** Sets the query conditions to the provided JSON object. */
1974
- setQuery(val: FilterQuery<DocType> | null): void;
1975
-
1976
- setUpdate(update: UpdateQuery<DocType> | UpdateWithAggregationPipeline): void;
1977
-
1978
- /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1979
- size(val: number): this;
1980
- size<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$size']): this;
1981
-
1982
- /** Specifies the number of documents to skip. */
1983
- skip(val: number): this;
1984
-
1985
- /** Specifies a `$slice` projection for an array. */
1986
- slice(val: number | Array<number>): this;
1987
- slice(path: string, val: number | Array<number>): this;
1988
-
1989
- /** Specifies this query as a `snapshot` query. */
1990
- snapshot(val?: boolean): this;
1991
-
1992
- /** Sets the sort order. If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. */
1993
- sort(arg: string | any): this;
1994
-
1995
- /** Sets the tailable option (for use with capped collections). */
1996
- tailable(bool?: boolean, opts?: {
1997
- numberOfRetries?: number;
1998
- tailableRetryInterval?: number;
1999
- }): this;
2000
-
2001
- /**
2002
- * Executes the query returning a `Promise` which will be
2003
- * resolved with either the doc(s) or rejected with the error.
2004
- */
2005
- then: Promise<ResultType>['then'];
2006
-
2007
- /** Converts this query to a customized, reusable query constructor with all arguments and options retained. */
2008
- toConstructor(): new (...args: any[]) => QueryWithHelpers<ResultType, DocType, THelpers, RawDocType>;
2009
-
2010
- /** Declare and/or execute this query as an update() operation. */
2011
- update(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
2012
-
2013
- /**
2014
- * Declare and/or execute this query as an updateMany() operation. Same as
2015
- * `update()`, except MongoDB will update _all_ documents that match
2016
- * `filter` (as opposed to just the first one) regardless of the value of
2017
- * the `multi` option.
2018
- */
2019
- updateMany(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
2020
-
2021
- /**
2022
- * Declare and/or execute this query as an updateOne() operation. Same as
2023
- * `update()`, except it does not support the `multi` or `overwrite` options.
2024
- */
2025
- updateOne(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
2026
-
2027
- /**
2028
- * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
2029
- * that must acknowledge this write before this write is considered successful.
2030
- */
2031
- w(val: string | number | null): this;
2032
-
2033
- /** Specifies a path for use with chaining. */
2034
- where(path: string, val?: any): this;
2035
- where(obj: object): this;
2036
- where(): this;
2037
-
2038
- /** Defines a `$within` or `$geoWithin` argument for geo-spatial queries. */
2039
- within(val?: any): this;
2040
-
2041
- /**
2042
- * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to
2043
- * wait for this write to propagate through the replica set before this
2044
- * operation fails. The default is `0`, which means no timeout.
2045
- */
2046
- wtimeout(ms: number): this;
2047
- }
2048
-
2049
403
  export type ProjectionElementType = number | string;
2050
404
  export type ProjectionType<T> = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
2051
405
 
2052
- export type QuerySelector<T> = {
2053
- // Comparison
2054
- $eq?: T;
2055
- $gt?: T;
2056
- $gte?: T;
2057
- $in?: [T] extends AnyArray<any> ? Unpacked<T>[] : T[];
2058
- $lt?: T;
2059
- $lte?: T;
2060
- $ne?: T;
2061
- $nin?: [T] extends AnyArray<any> ? Unpacked<T>[] : T[];
2062
- // Logical
2063
- $not?: T extends string ? QuerySelector<T> | RegExp : QuerySelector<T>;
2064
- // Element
2065
- /**
2066
- * When `true`, `$exists` matches the documents that contain the field,
2067
- * including documents where the field value is null.
2068
- */
2069
- $exists?: boolean;
2070
- $type?: string | number;
2071
- // Evaluation
2072
- $expr?: any;
2073
- $jsonSchema?: any;
2074
- $mod?: T extends number ? [number, number] : never;
2075
- $regex?: T extends string ? RegExp | string : never;
2076
- $options?: T extends string ? string : never;
2077
- // Geospatial
2078
- // TODO: define better types for geo queries
2079
- $geoIntersects?: { $geometry: object };
2080
- $geoWithin?: object;
2081
- $near?: object;
2082
- $nearSphere?: object;
2083
- $maxDistance?: number;
2084
- // Array
2085
- // TODO: define better types for $all and $elemMatch
2086
- $all?: T extends AnyArray<any> ? any[] : never;
2087
- $elemMatch?: T extends AnyArray<any> ? object : never;
2088
- $size?: T extends AnyArray<any> ? number : never;
2089
- // Bitwise
2090
- $bitsAllClear?: number | mongodb.Binary | number[];
2091
- $bitsAllSet?: number | mongodb.Binary | number[];
2092
- $bitsAnyClear?: number | mongodb.Binary | number[];
2093
- $bitsAnySet?: number | mongodb.Binary | number[];
2094
- };
406
+ export type SortValues = SortOrder;
2095
407
 
2096
- export type RootQuerySelector<T> = {
2097
- /** @see https://docs.mongodb.com/manual/reference/operator/query/and/#op._S_and */
2098
- $and?: Array<FilterQuery<T>>;
2099
- /** @see https://docs.mongodb.com/manual/reference/operator/query/nor/#op._S_nor */
2100
- $nor?: Array<FilterQuery<T>>;
2101
- /** @see https://docs.mongodb.com/manual/reference/operator/query/or/#op._S_or */
2102
- $or?: Array<FilterQuery<T>>;
2103
- /** @see https://docs.mongodb.com/manual/reference/operator/query/text */
2104
- $text?: {
2105
- $search: string;
2106
- $language?: string;
2107
- $caseSensitive?: boolean;
2108
- $diacriticSensitive?: boolean;
2109
- };
2110
- /** @see https://docs.mongodb.com/manual/reference/operator/query/where/#op._S_where */
2111
- $where?: string | Function;
2112
- /** @see https://docs.mongodb.com/manual/reference/operator/query/comment/#op._S_comment */
2113
- $comment?: string;
2114
- // we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name'
2115
- // this will mark all unrecognized properties as any (including nested queries)
2116
- [key: string]: any;
2117
- };
2118
-
2119
- export type ApplyBasicQueryCasting<T> = T | T[] | any;
2120
- export type Condition<T> = ApplyBasicQueryCasting<T> | QuerySelector<ApplyBasicQueryCasting<T>>;
2121
-
2122
- export type _FilterQuery<T> = {
2123
- [P in keyof T]?: Condition<T[P]>;
2124
- } &
2125
- RootQuerySelector<T>;
2126
-
2127
- /**
2128
- * Filter query to select the documents that match the query
2129
- * @example
2130
- * ```js
2131
- * { age: { $gte: 30 } }
2132
- * ```
2133
- */
2134
- export type FilterQuery<T> = _FilterQuery<T>;
2135
-
2136
- export type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
408
+ export type SortOrder = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2137
409
 
2138
410
  type _UpdateQuery<TSchema> = {
2139
411
  /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
@@ -2215,10 +487,10 @@ declare module 'mongoose' {
2215
487
  type LeanTypeOrArray<T> = T extends unknown[] ? LeanArray<T> : LeanType<T>;
2216
488
 
2217
489
  export type LeanArray<T extends unknown[]> =
2218
- // By checking if it extends Types.Array we can get the original base type before collapsing down,
2219
- // rather than trying to manually remove the old types. This matches both Array and DocumentArray
490
+ // By checking if it extends Types.Array we can get the original base type before collapsing down,
491
+ // rather than trying to manually remove the old types. This matches both Array and DocumentArray
2220
492
  T extends Types.Array<infer U> ? LeanTypeOrArray<U>[] :
2221
- // If it isn't a custom mongoose type we fall back to "do our best"
493
+ // If it isn't a custom mongoose type we fall back to "do our best"
2222
494
  T extends unknown[][] ? LeanArray<T[number]>[] : LeanType<T[number]>[];
2223
495
 
2224
496
  export type _LeanDocument<T> = {
@@ -2280,105 +552,6 @@ declare module 'mongoose' {
2280
552
  T extends Document ? LeanDocument<RawDocType> :
2281
553
  T;
2282
554
 
2283
- export class SchemaType<T = any> {
2284
- /** SchemaType constructor */
2285
- constructor(path: string, options?: AnyObject, instance?: string);
2286
-
2287
- /** Get/set the function used to cast arbitrary values to this type. */
2288
- static cast(caster?: Function | boolean): Function;
2289
-
2290
- static checkRequired(checkRequired?: (v: any) => boolean): (v: any) => boolean;
2291
-
2292
- /** Sets a default option for this schema type. */
2293
- static set(option: string, value: any): void;
2294
-
2295
- /** Attaches a getter for all instances of this schema type. */
2296
- static get(getter: (value: any) => any): void;
2297
-
2298
- /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */
2299
- OptionsConstructor: SchemaTypeOptions<T>;
2300
-
2301
- /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
2302
- cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
2303
-
2304
- /** Sets a default value for this SchemaType. */
2305
- default(val: any): any;
2306
-
2307
- /** Adds a getter to this schematype. */
2308
- get(fn: Function): this;
2309
-
2310
- /**
2311
- * Defines this path as immutable. Mongoose prevents you from changing
2312
- * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew).
2313
- */
2314
- immutable(bool: boolean): this;
2315
-
2316
- /** Declares the index options for this schematype. */
2317
- index(options: any): this;
2318
-
2319
- /** String representation of what type this is, like 'ObjectID' or 'Number' */
2320
- instance: string;
2321
-
2322
- /** True if this SchemaType has a required validator. False otherwise. */
2323
- isRequired?: boolean;
2324
-
2325
- /** The options this SchemaType was instantiated with */
2326
- options: AnyObject;
2327
-
2328
- /** The path to this SchemaType in a Schema. */
2329
- path: string;
2330
-
2331
- /**
2332
- * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
2333
- * looks at to determine the foreign collection it should query.
2334
- */
2335
- ref(ref: string | boolean | Model<any>): this;
2336
-
2337
- /**
2338
- * Adds a required validator to this SchemaType. The validator gets added
2339
- * to the front of this SchemaType's validators array using unshift().
2340
- */
2341
- required(required: boolean, message?: string): this;
2342
-
2343
- /** The schema this SchemaType instance is part of */
2344
- schema: Schema<any>;
2345
-
2346
- /** Sets default select() behavior for this path. */
2347
- select(val: boolean): this;
2348
-
2349
- /** Adds a setter to this schematype. */
2350
- set(fn: Function): this;
2351
-
2352
- /** Declares a sparse index. */
2353
- sparse(bool: boolean): this;
2354
-
2355
- /** Declares a full text index. */
2356
- text(bool: boolean): this;
2357
-
2358
- /** Defines a custom function for transforming this path when converting a document to JSON. */
2359
- transform(fn: (value: any) => any): this;
2360
-
2361
- /** Declares an unique index. */
2362
- unique(bool: boolean): this;
2363
-
2364
- /** The validators that Mongoose should run to validate properties at this SchemaType's path. */
2365
- validators: { message?: string; type?: string; validator?: Function }[];
2366
-
2367
- /** Adds validator(s) for this document path. */
2368
- validate(obj: RegExp | Function | any, errorMsg?: string,
2369
- type?: string): this;
2370
- }
2371
-
2372
- export interface SyncIndexesOptions extends mongodb.CreateIndexesOptions {
2373
- continueOnError?: boolean
2374
- }
2375
- export type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
2376
- export type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
2377
- export type Callback<T = any> = (error: CallbackError, result: T) => void;
2378
-
2379
- export type CallbackWithoutResult = (error: CallbackError) => void;
2380
- export type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2381
-
2382
555
  /* for ts-mongoose */
2383
556
  export class mquery { }
2384
557