mongoose 6.3.2 → 6.3.5

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