mongoose 6.2.4 → 6.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/types/index.d.ts CHANGED
@@ -1,11 +1,14 @@
1
- /// <reference path="./Error.d.ts" />
2
- /// <reference path="./PipelineStage.d.ts" />
3
- /// <reference path="./Connection.d.ts" />
1
+ /// <reference path="./connection.d.ts" />
2
+ /// <reference path="./cursor.d.ts" />
3
+ /// <reference path="./document.d.ts" />
4
+ /// <reference path="./error.d.ts" />
5
+ /// <reference path="./mongooseoptions.d.ts" />
6
+ /// <reference path="./pipelinestage.d.ts" />
7
+ /// <reference path="./schemaoptions.d.ts" />
4
8
 
5
9
  import events = require('events');
6
10
  import mongodb = require('mongodb');
7
11
  import mongoose = require('mongoose');
8
- import stream = require('stream');
9
12
 
10
13
  declare module 'mongoose' {
11
14
 
@@ -119,6 +122,13 @@ declare module 'mongoose' {
119
122
  export function isValidObjectId(v: Types.ObjectId): true;
120
123
  export function isValidObjectId(v: any): boolean;
121
124
 
125
+ /**
126
+ * Returns true if the given value is a Mongoose ObjectId (using `instanceof`) or if the
127
+ * given value is a 24 character hex string, which is the most commonly used string representation
128
+ * of an ObjectId.
129
+ */
130
+ export function isObjectIdOrHexString(v: any): boolean;
131
+
122
132
  export function model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
123
133
  export function model<T, U, TQueryHelpers = {}>(
124
134
  name: string,
@@ -165,117 +175,6 @@ declare module 'mongoose' {
165
175
 
166
176
  type Mongoose = typeof mongoose;
167
177
 
168
- interface MongooseOptions {
169
- /** true by default. Set to false to skip applying global plugins to child schemas */
170
- applyPluginsToChildSchemas?: boolean;
171
-
172
- /**
173
- * false by default. Set to true to apply global plugins to discriminator schemas.
174
- * This typically isn't necessary because plugins are applied to the base schema and
175
- * discriminators copy all middleware, methods, statics, and properties from the base schema.
176
- */
177
- applyPluginsToDiscriminators?: boolean;
178
-
179
- /**
180
- * Set to `true` to make Mongoose call` Model.createCollection()` automatically when you
181
- * create a model with `mongoose.model()` or `conn.model()`. This is useful for testing
182
- * transactions, change streams, and other features that require the collection to exist.
183
- */
184
- autoCreate?: boolean;
185
-
186
- /**
187
- * true by default. Set to false to disable automatic index creation
188
- * for all models associated with this Mongoose instance.
189
- */
190
- autoIndex?: boolean;
191
-
192
- /** enable/disable mongoose's buffering mechanism for all connections and models */
193
- bufferCommands?: boolean;
194
-
195
- bufferTimeoutMS?: number;
196
-
197
- /** false by default. Set to `true` to `clone()` all schemas before compiling into a model. */
198
- cloneSchemas?: boolean;
199
-
200
- /**
201
- * If `true`, prints the operations mongoose sends to MongoDB to the console.
202
- * If a writable stream is passed, it will log to that stream, without colorization.
203
- * If a callback function is passed, it will receive the collection name, the method
204
- * name, then all arguments passed to the method. For example, if you wanted to
205
- * replicate the default logging, you could output from the callback
206
- * `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`.
207
- */
208
- debug?:
209
- | boolean
210
- | { color?: boolean; shell?: boolean }
211
- | stream.Writable
212
- | ((collectionName: string, methodName: string, ...methodArgs: any[]) => void);
213
-
214
- /** If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query */
215
- maxTimeMS?: number;
216
-
217
- /**
218
- * true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that
219
- * returns `this` for convenience with populate. Set this to false to remove the getter.
220
- */
221
- objectIdGetter?: boolean;
222
-
223
- /**
224
- * Set to `true` to default to overwriting models with the same name when calling
225
- * `mongoose.model()`, as opposed to throwing an `OverwriteModelError`.
226
- */
227
- overwriteModels?: boolean;
228
-
229
- /**
230
- * If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`,
231
- * `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to
232
- * setting the `new` option to `true` for `findOneAndX()` calls by default. Read our
233
- * `findOneAndUpdate()` [tutorial](https://mongoosejs.com/docs/tutorials/findoneandupdate.html)
234
- * for more information.
235
- */
236
- returnOriginal?: boolean;
237
-
238
- /**
239
- * false by default. Set to true to enable [update validators](
240
- * https://mongoosejs.com/docs/validation.html#update-validators
241
- * ) for all validators by default.
242
- */
243
- runValidators?: boolean;
244
-
245
- sanitizeFilter?: boolean;
246
-
247
- sanitizeProjection?: boolean;
248
-
249
- /**
250
- * true by default. Set to false to opt out of Mongoose adding all fields that you `populate()`
251
- * to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one.
252
- */
253
- selectPopulatedPaths?: boolean;
254
-
255
- setDefaultsOnInsert?: boolean;
256
-
257
- /** true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas. */
258
- strict?: boolean | 'throw';
259
-
260
- /** true by default. set to `false` to allow populating paths that aren't in the schema */
261
- strictPopulate?: boolean;
262
-
263
- /**
264
- * false by default, may be `false`, `true`, or `'throw'`. Sets the default
265
- * [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery) mode for schemas.
266
- */
267
- strictQuery?: boolean | 'throw';
268
-
269
- /**
270
- * `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to
271
- * `toJSON()`, for determining how Mongoose documents get serialized by `JSON.stringify()`
272
- */
273
- toJSON?: ToObjectOptions;
274
-
275
- /** `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to `toObject()` */
276
- toObject?: ToObjectOptions;
277
- }
278
-
279
178
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
280
179
  interface ClientSession extends mongodb.ClientSession { }
281
180
 
@@ -322,247 +221,8 @@ declare module 'mongoose' {
322
221
  getIndexes(): any;
323
222
  }
324
223
 
325
- class Document<T = any, TQueryHelpers = any, DocType = any> {
326
- constructor(doc?: any);
327
-
328
- /** This documents _id. */
329
- _id?: T;
330
-
331
- /** This documents __v. */
332
- __v?: any;
333
-
334
- /* Get all subdocs (by bfs) */
335
- $getAllSubdocs(): Document[];
336
-
337
- /** Don't run validation on this path or persist changes to this path. */
338
- $ignore(path: string): void;
339
-
340
- /** Checks if a path is set to its default. */
341
- $isDefault(path: string): boolean;
342
-
343
- /** Getter/setter, determines whether the document was removed or not. */
344
- $isDeleted(val?: boolean): boolean;
345
-
346
- /** Returns an array of all populated documents associated with the query */
347
- $getPopulatedDocs(): Document[];
348
-
349
- /**
350
- * Returns true if the given path is nullish or only contains empty objects.
351
- * Useful for determining whether this subdoc will get stripped out by the
352
- * [minimize option](/docs/guide.html#minimize).
353
- */
354
- $isEmpty(path: string): boolean;
355
-
356
- /** Checks if a path is invalid */
357
- $isValid(path: string): boolean;
358
-
359
- /**
360
- * Empty object that you can use for storing properties on the document. This
361
- * is handy for passing data to middleware without conflicting with Mongoose
362
- * internals.
363
- */
364
- $locals: Record<string, unknown>;
365
-
366
- /** Marks a path as valid, removing existing validation errors. */
367
- $markValid(path: string): void;
368
-
369
- /**
370
- * A string containing the current operation that Mongoose is executing
371
- * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`.
372
- */
373
- $op: string | null;
374
-
375
- /**
376
- * Getter/setter around the session associated with this document. Used to
377
- * automatically set `session` if you `save()` a doc that you got from a
378
- * query with an associated session.
379
- */
380
- $session(session?: mongodb.ClientSession | null): mongodb.ClientSession;
381
-
382
- /** Alias for `set()`, used internally to avoid conflicts */
383
- $set(path: string, val: any, options?: any): this;
384
- $set(path: string, val: any, type: any, options?: any): this;
385
- $set(value: any): this;
386
-
387
- /** Set this property to add additional query filters when Mongoose saves this document and `isNew` is false. */
388
- $where: Record<string, unknown>;
389
-
390
- /** If this is a discriminator model, `baseModelName` is the name of the base model. */
391
- baseModelName?: string;
392
-
393
- /** Collection the model uses. */
394
- collection: Collection;
395
-
396
- /** Connection the model uses. */
397
- db: Connection;
398
-
399
- /** Removes this document from the db. */
400
- delete(options?: QueryOptions): QueryWithHelpers<any, this, TQueryHelpers>;
401
- delete(options: QueryOptions, cb?: Callback): void;
402
- delete(cb: Callback): void;
403
-
404
- /** Removes this document from the db. */
405
- deleteOne(options?: QueryOptions): QueryWithHelpers<any, this, TQueryHelpers>;
406
- deleteOne(options: QueryOptions, cb?: Callback): void;
407
- deleteOne(cb: Callback): void;
408
-
409
- /**
410
- * Takes a populated field and returns it to its unpopulated state. If called with
411
- * no arguments, then all populated fields are returned to their unpopulated state.
412
- */
413
- depopulate(path?: string | string[]): this;
414
-
415
- /**
416
- * Returns the list of paths that have been directly modified. A direct
417
- * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`,
418
- * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`.
419
- */
420
- directModifiedPaths(): Array<string>;
421
-
422
- /**
423
- * Returns true if this document is equal to another document.
424
- *
425
- * Documents are considered equal when they have matching `_id`s, unless neither
426
- * document has an `_id`, in which case this function falls back to using
427
- * `deepEqual()`.
428
- */
429
- equals(doc: Document<T>): boolean;
430
-
431
- /** Hash containing current validation errors. */
432
- errors?: Error.ValidationError;
433
-
434
- /** Returns the value of a path. */
435
- get(path: string, type?: any, options?: any): any;
436
-
437
- /**
438
- * Returns the changes that happened to the document
439
- * in the format that will be sent to MongoDB.
440
- */
441
- getChanges(): UpdateQuery<this>;
442
-
443
- /** The string version of this documents _id. */
444
- id?: any;
445
-
446
- /** Signal that we desire an increment of this documents version. */
447
- increment(): this;
448
-
449
- /**
450
- * Initializes the document without setters or marking anything modified.
451
- * Called internally after a document is returned from mongodb. Normally,
452
- * you do **not** need to call this function on your own.
453
- */
454
- init(obj: any, opts?: any, cb?: Callback<this>): this;
455
-
456
- /** Marks a path as invalid, causing validation to fail. */
457
- invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null;
458
-
459
- /** Returns true if `path` was directly set and modified, else false. */
460
- isDirectModified(path: string): boolean;
461
-
462
- /** Checks if `path` was explicitly selected. If no projection, always returns true. */
463
- isDirectSelected(path: string): boolean;
464
-
465
- /** Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. */
466
- isInit(path: string): boolean;
467
-
468
- /**
469
- * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path
470
- * in this document is modified.
471
- */
472
- isModified(path?: string | Array<string>): boolean;
473
-
474
- /** Boolean flag specifying if the document is new. */
475
- isNew: boolean;
476
-
477
- /** Checks if `path` was selected in the source query which initialized this document. */
478
- isSelected(path: string): boolean;
479
-
480
- /** Marks the path as having pending changes to write to the db. */
481
- markModified(path: string, scope?: any): void;
482
-
483
- /** Returns the list of paths that have been modified. */
484
- modifiedPaths(options?: { includeChildren?: boolean }): Array<string>;
485
-
486
- /** The name of the model */
487
- modelName: string;
488
-
489
- /**
490
- * Overwrite all values in this document with the values of `obj`, except
491
- * for immutable properties. Behaves similarly to `set()`, except for it
492
- * unsets all properties that aren't in `obj`.
493
- */
494
- overwrite(obj: AnyObject): this;
495
-
496
- /**
497
- * If this document is a subdocument or populated document, returns the
498
- * document's parent. Returns undefined otherwise.
499
- */
500
- $parent(): Document | undefined;
501
-
502
- /** Populates document references. */
503
- populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<this & Paths>;
504
- populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[], callback: Callback<this & Paths>): void;
505
- populate<Paths = {}>(path: string, names: string): Promise<this & Paths>;
506
- populate<Paths = {}>(path: string, names: string, callback: Callback<this & Paths>): void;
507
-
508
- /** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */
509
- populated(path: string): any;
510
-
511
- /** Removes this document from the db. */
512
- remove(options?: QueryOptions): Promise<this>;
513
- remove(options?: QueryOptions, cb?: Callback): void;
514
-
515
- /** Sends a replaceOne command with this document `_id` as the query selector. */
516
- replaceOne(replacement?: AnyObject, options?: QueryOptions | null, callback?: Callback): Query<any, this>;
517
- replaceOne(replacement?: AnyObject, options?: QueryOptions | null, callback?: Callback): Query<any, this>;
518
-
519
- /** Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. */
520
- save(options?: SaveOptions): Promise<this>;
521
- save(options?: SaveOptions, fn?: Callback<this>): void;
522
- save(fn?: Callback<this>): void;
523
-
524
- /** The document's schema. */
525
- schema: Schema;
526
-
527
- /** Sets the value of a path, or many paths. */
528
- set(path: string, val: any, options?: any): this;
529
- set(path: string, val: any, type: any, options?: any): this;
530
- set(value: any): this;
531
-
532
- /** The return value of this method is used in calls to JSON.stringify(doc). */
533
- toJSON(options: ToObjectOptions & { flattenMaps: false }): LeanDocument<this>;
534
- toJSON(options?: ToObjectOptions): FlattenMaps<LeanDocument<this>>;
535
- toJSON<T = FlattenMaps<DocType>>(options?: ToObjectOptions): T;
536
-
537
- /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
538
- toObject(options?: ToObjectOptions): LeanDocument<this>;
539
- toObject<T = DocType>(options?: ToObjectOptions): T;
540
-
541
- /** Clears the modified state on the specified path. */
542
- unmarkModified(path: string): void;
543
-
544
- /** Sends an update command with this document `_id` as the query selector. */
545
- update(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): Query<any, this>;
546
-
547
- /** Sends an updateOne command with this document `_id` as the query selector. */
548
- updateOne(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): Query<any, this>;
549
-
550
- /** Executes registered validation rules for this document. */
551
- validate(options:{ pathsToSkip?: pathsToSkip }): Promise<void>;
552
- validate(pathsToValidate?: pathsToValidate, options?: any): Promise<void>;
553
- validate(callback: CallbackWithoutResult): void;
554
- validate(pathsToValidate: pathsToValidate, callback: CallbackWithoutResult): void;
555
- validate(pathsToValidate: pathsToValidate, options: any, callback: CallbackWithoutResult): void;
556
-
557
- /** Executes registered validation rules (skipping asynchronous validators) for this document. */
558
- validateSync(options:{pathsToSkip?: pathsToSkip, [k:string]: any }): Error.ValidationError | null;
559
- validateSync(pathsToValidate?: Array<string>, options?: any): Error.ValidationError | null;
560
- }
561
-
562
224
  /** A list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. */
563
225
  type pathsToValidate = string[] | string;
564
- /** A list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. */
565
- type pathsToSkip = string[] | string;
566
226
 
567
227
  interface AcceptsDiscriminator {
568
228
  /** Adds a discriminator type. */
@@ -650,8 +310,8 @@ declare module 'mongoose' {
650
310
  * mongoose will not create the collection for the model until any documents are
651
311
  * created. Use this method to create the collection explicitly.
652
312
  */
653
- createCollection<T>(options?: mongodb.CreateCollectionOptions): Promise<mongodb.Collection<T>>;
654
- createCollection<T>(options: mongodb.CreateCollectionOptions | null, callback: Callback<mongodb.Collection<T>>): void;
313
+ createCollection<T>(options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>): Promise<mongodb.Collection<T>>;
314
+ createCollection<T>(options: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'> | null, callback: Callback<mongodb.Collection<T>>): void;
655
315
 
656
316
  /**
657
317
  * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)
@@ -1092,10 +752,10 @@ declare module 'mongoose' {
1092
752
  type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
1093
753
  type IndexDefinition = Record<string, IndexDirection>;
1094
754
 
1095
- type PreMiddlewareFunction<T> = (this: T, next: (err?: CallbackError) => void) => void | Promise<void>;
1096
- type PreSaveMiddlewareFunction<T> = (this: T, next: (err?: CallbackError) => void, opts: SaveOptions) => void | Promise<void>;
1097
- type PostMiddlewareFunction<ThisType, ResType = any> = (this: ThisType, res: ResType, next: (err?: CallbackError) => void) => void | Promise<void>;
1098
- type ErrorHandlingMiddlewareFunction<ThisType, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: (err?: CallbackError) => void) => void;
755
+ export type PreMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
756
+ export type PreSaveMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError, opts: SaveOptions) => void | Promise<void>;
757
+ export type PostMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
758
+ export type ErrorHandlingMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void;
1099
759
 
1100
760
  class Schema<DocType = any, M = Model<DocType, any, any, any>, TInstanceMethods = any, TQueryHelpers = any> extends events.EventEmitter {
1101
761
  /**
@@ -1226,7 +886,7 @@ declare module 'mongoose' {
1226
886
  statics: { [name: string]: (this: M, ...args: any[]) => any };
1227
887
 
1228
888
  /** Creates a virtual type with the given name. */
1229
- virtual(name: string, options?: VirtualTypeOptions): VirtualType;
889
+ virtual<T = HydratedDocument<DocType, TInstanceMethods>>(name: string, options?: VirtualTypeOptions<T>): VirtualType;
1230
890
 
1231
891
  /** Object of currently defined virtuals on this schema */
1232
892
  virtuals: any;
@@ -1256,183 +916,16 @@ declare module 'mongoose' {
1256
916
  typeof SchemaType |
1257
917
  Schema<any, any, any> |
1258
918
  Schema<any, any, any>[] |
1259
- SchemaTypeOptions<T extends undefined ? any : T>[] |
919
+ SchemaTypeOptions<T extends undefined ? any : Unpacked<T>>[] |
1260
920
  Function[] |
1261
921
  SchemaDefinition<T> |
1262
- SchemaDefinition<T>[] |
922
+ SchemaDefinition<Unpacked<T>>[] |
1263
923
  typeof SchemaTypes.Mixed;
1264
924
 
1265
925
  type SchemaDefinition<T = undefined> = T extends undefined
1266
926
  ? { [path: string]: SchemaDefinitionProperty; }
1267
927
  : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
1268
928
 
1269
- interface SchemaOptions {
1270
- /**
1271
- * By default, Mongoose's init() function creates all the indexes defined in your model's schema by
1272
- * calling Model.createIndexes() after you successfully connect to MongoDB. If you want to disable
1273
- * automatic index builds, you can set autoIndex to false.
1274
- */
1275
- autoIndex?: boolean;
1276
- /**
1277
- * If set to `true`, Mongoose will call Model.createCollection() to create the underlying collection
1278
- * in MongoDB if autoCreate is set to true. Calling createCollection() sets the collection's default
1279
- * collation based on the collation option and establishes the collection as a capped collection if
1280
- * you set the capped schema option.
1281
- */
1282
- autoCreate?: boolean;
1283
- /**
1284
- * By default, mongoose buffers commands when the connection goes down until the driver manages to reconnect.
1285
- * To disable buffering, set bufferCommands to false.
1286
- */
1287
- bufferCommands?: boolean;
1288
- /**
1289
- * If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before
1290
- * throwing an error. If not specified, Mongoose will use 10000 (10 seconds).
1291
- */
1292
- bufferTimeoutMS?: number;
1293
- /**
1294
- * Mongoose supports MongoDBs capped collections. To specify the underlying MongoDB collection be capped, set
1295
- * the capped option to the maximum size of the collection in bytes.
1296
- */
1297
- capped?: boolean | number | { size?: number; max?: number; autoIndexId?: boolean; };
1298
- /** Sets a default collation for every query and aggregation. */
1299
- collation?: mongodb.CollationOptions;
1300
-
1301
- /** The timeseries option to use when creating the model's collection. */
1302
- timeseries?: mongodb.TimeSeriesCollectionOptions;
1303
-
1304
- /**
1305
- * Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName
1306
- * method. This method pluralizes the name. Set this option if you need a different name for your collection.
1307
- */
1308
- collection?: string;
1309
- /**
1310
- * When you define a [discriminator](/docs/discriminators.html), Mongoose adds a path to your
1311
- * schema that stores which discriminator a document is an instance of. By default, Mongoose
1312
- * adds an `__t` path, but you can set `discriminatorKey` to overwrite this default.
1313
- */
1314
- discriminatorKey?: string;
1315
- /** defaults to false. */
1316
- emitIndexErrors?: boolean;
1317
- excludeIndexes?: any;
1318
- /**
1319
- * Mongoose assigns each of your schemas an id virtual getter by default which returns the document's _id field
1320
- * cast to a string, or in the case of ObjectIds, its hexString.
1321
- */
1322
- id?: boolean;
1323
- /**
1324
- * Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema
1325
- * constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior. If you
1326
- * don't want an _id added to your schema at all, you may disable it using this option.
1327
- */
1328
- _id?: boolean;
1329
- /**
1330
- * Mongoose will, by default, "minimize" schemas by removing empty objects. This behavior can be
1331
- * overridden by setting minimize option to false. It will then store empty objects.
1332
- */
1333
- minimize?: boolean;
1334
- /**
1335
- * Optimistic concurrency is a strategy to ensure the document you're updating didn't change between when you
1336
- * loaded it using find() or findOne(), and when you update it using save(). Set to `true` to enable
1337
- * optimistic concurrency.
1338
- */
1339
- optimisticConcurrency?: boolean;
1340
- /**
1341
- * If `plugin()` called with tags, Mongoose will only apply plugins to schemas that have
1342
- * a matching tag in `pluginTags`
1343
- */
1344
- pluginTags?: string[];
1345
- /**
1346
- * Allows setting query#read options at the schema level, providing us a way to apply default ReadPreferences
1347
- * to all queries derived from a model.
1348
- */
1349
- read?: string;
1350
- /** Allows setting write concern at the schema level. */
1351
- writeConcern?: WriteConcern;
1352
- /** defaults to true. */
1353
- safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean };
1354
- /**
1355
- * The shardKey option is used when we have a sharded MongoDB architecture. Each sharded collection is
1356
- * given a shard key which must be present in all insert/update operations. We just need to set this
1357
- * schema option to the same shard key and we'll be all set.
1358
- */
1359
- shardKey?: Record<string, unknown>;
1360
- /**
1361
- * The strict option, (enabled by default), ensures that values passed to our model constructor that were not
1362
- * specified in our schema do not get saved to the db.
1363
- */
1364
- strict?: boolean | 'throw';
1365
- /**
1366
- * equal to `strict` by default, may be `false`, `true`, or `'throw'`. Sets the default
1367
- * [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery) mode for schemas.
1368
- */
1369
- strictQuery?: boolean | 'throw';
1370
- /** Exactly the same as the toObject option but only applies when the document's toJSON method is called. */
1371
- toJSON?: ToObjectOptions;
1372
- /**
1373
- * Documents have a toObject method which converts the mongoose document into a plain JavaScript object.
1374
- * This method accepts a few options. Instead of applying these options on a per-document basis, we may
1375
- * declare the options at the schema level and have them applied to all of the schema's documents by
1376
- * default.
1377
- */
1378
- toObject?: ToObjectOptions;
1379
- /**
1380
- * By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a
1381
- * type declaration. However, for applications like geoJSON, the 'type' property is important. If you want to
1382
- * control which key mongoose uses to find type declarations, set the 'typeKey' schema option.
1383
- */
1384
- typeKey?: string;
1385
-
1386
- /**
1387
- * By default, documents are automatically validated before they are saved to the database. This is to
1388
- * prevent saving an invalid document. If you want to handle validation manually, and be able to save
1389
- * objects which don't pass validation, you can set validateBeforeSave to false.
1390
- */
1391
- validateBeforeSave?: boolean;
1392
- /**
1393
- * The versionKey is a property set on each document when first created by Mongoose. This keys value
1394
- * contains the internal revision of the document. The versionKey option is a string that represents
1395
- * the path to use for versioning. The default is '__v'.
1396
- */
1397
- versionKey?: string | boolean;
1398
- /**
1399
- * By default, Mongoose will automatically select() any populated paths for you, unless you explicitly exclude them.
1400
- */
1401
- selectPopulatedPaths?: boolean;
1402
- /**
1403
- * skipVersioning allows excluding paths from versioning (i.e., the internal revision will not be
1404
- * incremented even if these paths are updated). DO NOT do this unless you know what you're doing.
1405
- * For subdocuments, include this on the parent document using the fully qualified path.
1406
- */
1407
- skipVersioning?: any;
1408
- /**
1409
- * Validation errors in a single nested schema are reported
1410
- * both on the child and on the parent schema.
1411
- * Set storeSubdocValidationError to false on the child schema
1412
- * to make Mongoose only report the parent error.
1413
- */
1414
- storeSubdocValidationError?: boolean;
1415
- /**
1416
- * The timestamps option tells mongoose to assign createdAt and updatedAt fields to your schema. The type
1417
- * assigned is Date. By default, the names of the fields are createdAt and updatedAt. Customize the
1418
- * field names by setting timestamps.createdAt and timestamps.updatedAt.
1419
- */
1420
- timestamps?: boolean | SchemaTimestampsConfig;
1421
-
1422
- /**
1423
- * Using `save`, `isNew`, and other Mongoose reserved names as schema path names now triggers a warning, not an error.
1424
- * You can suppress the warning by setting { supressReservedKeysWarning: true } schema options. Keep in mind that this
1425
- * can break plugins that rely on these reserved names.
1426
- */
1427
- supressReservedKeysWarning?: boolean
1428
- }
1429
-
1430
- interface SchemaTimestampsConfig {
1431
- createdAt?: boolean | string;
1432
- updatedAt?: boolean | string;
1433
- currentTime?: () => (NativeDate | number);
1434
- }
1435
-
1436
929
  type Unpacked<T> = T extends (infer U)[] ?
1437
930
  U :
1438
931
  T extends ReadonlyArray<infer U> ? U : T;
@@ -1657,15 +1150,15 @@ declare module 'mongoose' {
1657
1150
 
1658
1151
  type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1659
1152
 
1660
- interface VirtualTypeOptions {
1153
+ interface VirtualTypeOptions<HydratedDocType = Document> {
1661
1154
  /** If `ref` is not nullish, this becomes a populated virtual. */
1662
1155
  ref?: string | Function;
1663
1156
 
1664
1157
  /** The local field to populate on if this is a populated virtual. */
1665
- localField?: string | Function;
1158
+ localField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string);
1666
1159
 
1667
1160
  /** The foreign field to populate on if this is a populated virtual. */
1668
- foreignField?: string | Function;
1161
+ foreignField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string);
1669
1162
 
1670
1163
  /**
1671
1164
  * By default, a populated virtual is an array. If you set `justOne`,
@@ -1972,8 +1465,11 @@ declare module 'mongoose' {
1972
1465
 
1973
1466
  type QueryWithHelpers<ResultType, DocType, THelpers = {}, RawDocType = DocType> = Query<ResultType, DocType, THelpers, RawDocType> & THelpers;
1974
1467
 
1975
- type UnpackedIntersection<T, U> = T extends (infer V)[] ? (V & U)[] : T & U;
1976
- type UnpackedIntersectionWithNull<T, U> = T extends null ? UnpackedIntersection<T, U> | null : UnpackedIntersection<T, U>;
1468
+ type UnpackedIntersection<T, U> = T extends (infer A)[]
1469
+ ? (Omit<A, keyof U> & U)[]
1470
+ : keyof U extends never
1471
+ ? T
1472
+ : Omit<T, keyof U> & U;
1977
1473
 
1978
1474
  type ProjectionFields<DocType> = {[Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any} & Record<string, any>;
1979
1475
 
@@ -2053,7 +1549,7 @@ declare module 'mongoose' {
2053
1549
  * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
2054
1550
  * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
2055
1551
  */
2056
- cursor(options?: any): QueryCursor<DocType>;
1552
+ cursor(options?: QueryOptions): Cursor<DocType, QueryOptions>;
2057
1553
 
2058
1554
  /**
2059
1555
  * Declare and/or execute this query as a `deleteMany()` operation. Works like
@@ -2274,8 +1770,8 @@ declare module 'mongoose' {
2274
1770
  polygon(path: string, ...coordinatePairs: number[][]): this;
2275
1771
 
2276
1772
  /** Specifies paths which should be populated with other documents. */
2277
- populate<Paths = {}>(path: string | any, select?: string | any, model?: string | Model<any, THelpers>, match?: any): QueryWithHelpers<UnpackedIntersectionWithNull<ResultType, Paths>, DocType, THelpers, RawDocType>;
2278
- populate<Paths = {}>(options: PopulateOptions | Array<PopulateOptions>): QueryWithHelpers<UnpackedIntersectionWithNull<ResultType, Paths>, DocType, THelpers, RawDocType>;
1773
+ populate<Paths = {}>(path: string | string[], select?: string | any, model?: string | Model<any, THelpers>, match?: any): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, RawDocType>;
1774
+ populate<Paths = {}>(options: PopulateOptions | (PopulateOptions | string)[]): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, RawDocType>;
2279
1775
 
2280
1776
  /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */
2281
1777
  projection(): ProjectionFields<DocType> | null;
@@ -2500,7 +1996,7 @@ declare module 'mongoose' {
2500
1996
  $each: Type;
2501
1997
  };
2502
1998
 
2503
- type SortValues = -1 | 1 | 'asc' | 'desc';
1999
+ type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2504
2000
 
2505
2001
  type ArrayOperator<Type> = {
2506
2002
  $each: Type;
@@ -2618,49 +2114,6 @@ declare module 'mongoose' {
2618
2114
  T extends Document ? RawDocType :
2619
2115
  T;
2620
2116
 
2621
- class QueryCursor<DocType> extends stream.Readable {
2622
- [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
2623
-
2624
- /**
2625
- * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
2626
- * Useful for setting the `noCursorTimeout` and `tailable` flags.
2627
- */
2628
- addCursorFlag(flag: string, value: boolean): this;
2629
-
2630
- /**
2631
- * Marks this cursor as closed. Will stop streaming and subsequent calls to
2632
- * `next()` will error.
2633
- */
2634
- close(): Promise<void>;
2635
- close(callback: CallbackWithoutResult): void;
2636
-
2637
- /**
2638
- * Execute `fn` for every document(s) in the cursor. If batchSize is provided
2639
- * `fn` will be executed for each batch of documents. If `fn` returns a promise,
2640
- * will wait for the promise to resolve before iterating on to the next one.
2641
- * Returns a promise that resolves when done.
2642
- */
2643
- eachAsync(fn: (doc: DocType) => any, options?: { parallel?: number }): Promise<void>;
2644
- eachAsync(fn: (doc: DocType[]) => any, options: { parallel?: number, batchSize: number }): Promise<void>;
2645
- eachAsync(fn: (doc: DocType) => any, options?: { parallel?: number, batchSize?: number }, cb?: CallbackWithoutResult): void;
2646
- eachAsync(fn: (doc: DocType[]) => any, options: { parallel?: number, batchSize: number }, cb?: CallbackWithoutResult): void;
2647
-
2648
- /**
2649
- * Registers a transform function which subsequently maps documents retrieved
2650
- * via the streams interface or `.next()`
2651
- */
2652
- map<ResultType>(fn: (res: DocType) => ResultType): QueryCursor<ResultType>;
2653
-
2654
- /**
2655
- * Get the next document from this cursor. Will return `null` when there are
2656
- * no documents left.
2657
- */
2658
- next(): Promise<DocType>;
2659
- next(callback: Callback<DocType | null>): void;
2660
-
2661
- options: any;
2662
- }
2663
-
2664
2117
  class Aggregate<R> {
2665
2118
  /**
2666
2119
  * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js
@@ -2702,7 +2155,7 @@ declare module 'mongoose' {
2702
2155
  /**
2703
2156
  * Sets the cursor option for the aggregation query (ignored for < 2.6.0).
2704
2157
  */
2705
- cursor(options?: Record<string, unknown>): AggregationCursor;
2158
+ cursor<DocType = any>(options?: Record<string, unknown>): Cursor<DocType>;
2706
2159
 
2707
2160
  /** Executes the aggregate pipeline on the currently bound Model. */
2708
2161
  exec(callback?: Callback<R>): Promise<R>;
@@ -2790,7 +2243,7 @@ declare module 'mongoose' {
2790
2243
  skip(num: number): this;
2791
2244
 
2792
2245
  /** Appends a new $sort operator to this aggregate pipeline. */
2793
- sort(arg: PipelineStage.Sort['$sort']): this;
2246
+ sort(arg: string | Record<string, SortValues> | PipelineStage.Sort['$sort']): this;
2794
2247
 
2795
2248
  /** Provides promise for aggregate. */
2796
2249
  then: Promise<R>['then'];
@@ -2808,43 +2261,6 @@ declare module 'mongoose' {
2808
2261
  unwind(...args: PipelineStage.Unwind['$unwind'][]): this;
2809
2262
  }
2810
2263
 
2811
- class AggregationCursor extends stream.Readable {
2812
- /**
2813
- * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
2814
- * Useful for setting the `noCursorTimeout` and `tailable` flags.
2815
- */
2816
- addCursorFlag(flag: string, value: boolean): this;
2817
-
2818
- /**
2819
- * Marks this cursor as closed. Will stop streaming and subsequent calls to
2820
- * `next()` will error.
2821
- */
2822
- close(): Promise<void>;
2823
- close(callback: CallbackWithoutResult): void;
2824
-
2825
- /**
2826
- * Execute `fn` for every document(s) in the cursor. If batchSize is provided
2827
- * `fn` will be executed for each batch of documents. If `fn` returns a promise,
2828
- * will wait for the promise to resolve before iterating on to the next one.
2829
- * Returns a promise that resolves when done.
2830
- */
2831
- eachAsync(fn: (doc: any) => any, options?: { parallel?: number, batchSize?: number }): Promise<void>;
2832
- eachAsync(fn: (doc: any) => any, options?: { parallel?: number, batchSize?: number }, cb?: CallbackWithoutResult): void;
2833
-
2834
- /**
2835
- * Registers a transform function which subsequently maps documents retrieved
2836
- * via the streams interface or `.next()`
2837
- */
2838
- map(fn: (res: any) => any): this;
2839
-
2840
- /**
2841
- * Get the next document from this cursor. Will return `null` when there are
2842
- * no documents left.
2843
- */
2844
- next(): Promise<any>;
2845
- next(callback: Callback): void;
2846
- }
2847
-
2848
2264
  class SchemaType {
2849
2265
  /** SchemaType constructor */
2850
2266
  constructor(path: string, options?: AnyObject, instance?: string);
@@ -2942,6 +2358,7 @@ declare module 'mongoose' {
2942
2358
  type Callback<T = any> = (error: CallbackError, result: T) => void;
2943
2359
 
2944
2360
  type CallbackWithoutResult = (error: CallbackError) => void;
2361
+ type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2945
2362
 
2946
2363
  /* for ts-mongoose */
2947
2364
  class mquery {}