mongoose 6.2.3 → 6.2.4

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,5 +1,6 @@
1
1
  /// <reference path="./Error.d.ts" />
2
2
  /// <reference path="./PipelineStage.d.ts" />
3
+ /// <reference path="./Connection.d.ts" />
3
4
 
4
5
  import events = require('events');
5
6
  import mongodb = require('mongodb');
@@ -8,14 +9,6 @@ import stream = require('stream');
8
9
 
9
10
  declare module 'mongoose' {
10
11
 
11
- export enum ConnectionStates {
12
- disconnected = 0,
13
- connected = 1,
14
- connecting = 2,
15
- disconnecting = 3,
16
- uninitialized = 99,
17
- }
18
-
19
12
  class NativeDate extends global.Date {}
20
13
 
21
14
  /** The Mongoose Date [SchemaType](/docs/schematypes.html). */
@@ -64,9 +57,6 @@ declare module 'mongoose' {
64
57
  /** The various Mongoose SchemaTypes. */
65
58
  export const SchemaTypes: typeof Schema.Types;
66
59
 
67
- /** Expose connection states for user-land */
68
- export const STATES: typeof ConnectionStates;
69
-
70
60
  /** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
71
61
  export function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
72
62
  export function connect(uri: string, callback: CallbackWithoutResult): void;
@@ -100,10 +90,11 @@ declare module 'mongoose' {
100
90
 
101
91
  /** An array containing all models associated with this Mongoose instance. */
102
92
  export const models: Models;
93
+
103
94
  /** Creates a Connection instance. */
95
+ export function createConnection(uri: string, options: ConnectOptions, callback: Callback<Connection>): void;
104
96
  export function createConnection(uri: string, options?: ConnectOptions): Connection;
105
97
  export function createConnection(): Connection;
106
- export function createConnection(uri: string, options: ConnectOptions, callback: Callback<Connection>): void;
107
98
 
108
99
  /**
109
100
  * Removes the model named `name` from the default connection, if it exists.
@@ -288,190 +279,6 @@ declare module 'mongoose' {
288
279
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
289
280
  interface ClientSession extends mongodb.ClientSession { }
290
281
 
291
- interface ConnectOptions extends mongodb.MongoClientOptions {
292
- /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
293
- bufferCommands?: boolean;
294
- /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
295
- dbName?: string;
296
- /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
297
- user?: string;
298
- /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
299
- pass?: string;
300
- /** Set to false to disable automatic index creation for all models associated with this connection. */
301
- autoIndex?: boolean;
302
- /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
303
- autoCreate?: boolean;
304
- }
305
-
306
- class Connection extends events.EventEmitter {
307
- /** Returns a promise that resolves when this connection successfully connects to MongoDB */
308
- asPromise(): Promise<this>;
309
-
310
- /** Closes the connection */
311
- close(callback: CallbackWithoutResult): void;
312
- close(force: boolean, callback: CallbackWithoutResult): void;
313
- close(force?: boolean): Promise<void>;
314
-
315
- /** Retrieves a collection, creating it if not cached. */
316
- collection<T = AnyObject>(name: string, options?: mongodb.CreateCollectionOptions): Collection<T>;
317
-
318
- /** A hash of the collections associated with this connection */
319
- collections: { [index: string]: Collection };
320
-
321
- /** A hash of the global options that are associated with this connection */
322
- config: any;
323
-
324
- /** The mongodb.Db instance, set when the connection is opened */
325
- db: mongodb.Db;
326
-
327
- /**
328
- * Helper for `createCollection()`. Will explicitly create the given collection
329
- * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/)
330
- * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
331
- */
332
- createCollection<T = AnyObject>(name: string, options?: mongodb.CreateCollectionOptions): Promise<mongodb.Collection<T>>;
333
- createCollection<T = AnyObject>(name: string, cb: Callback<mongodb.Collection<T>>): void;
334
- createCollection<T = AnyObject>(name: string, options: mongodb.CreateCollectionOptions, cb?: Callback<mongodb.Collection<T>>): Promise<mongodb.Collection<T>>;
335
-
336
- /**
337
- * Removes the model named `name` from this connection, if it exists. You can
338
- * use this function to clean up any models you created in your tests to
339
- * prevent OverwriteModelErrors.
340
- */
341
- deleteModel(name: string): this;
342
-
343
- /**
344
- * Helper for `dropCollection()`. Will delete the given collection, including
345
- * all documents and indexes.
346
- */
347
- dropCollection(collection: string): Promise<void>;
348
- dropCollection(collection: string, cb: CallbackWithoutResult): void;
349
-
350
- /**
351
- * Helper for `dropDatabase()`. Deletes the given database, including all
352
- * collections, documents, and indexes.
353
- */
354
- dropDatabase(): Promise<void>;
355
- dropDatabase(cb: CallbackWithoutResult): void;
356
-
357
- /** Gets the value of the option `key`. Equivalent to `conn.options[key]` */
358
- get(key: string): any;
359
-
360
- /**
361
- * Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
362
- * that this connection uses to talk to MongoDB.
363
- */
364
- getClient(): mongodb.MongoClient;
365
-
366
- /**
367
- * The host name portion of the URI. If multiple hosts, such as a replica set,
368
- * this will contain the first host name in the URI
369
- */
370
- host: string;
371
-
372
- /**
373
- * A number identifier for this connection. Used for debugging when
374
- * you have [multiple connections](/docs/connections.html#multiple_connections).
375
- */
376
- id: number;
377
-
378
- /**
379
- * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
380
- * a map from model names to models. Contains all models that have been
381
- * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model).
382
- */
383
- models: { [index: string]: Model<any> };
384
-
385
- /** Defines or retrieves a model. */
386
- model<T>(name: string, schema?: Schema<any>, collection?: string, options?: CompileModelOptions): Model<T>;
387
- model<T, U, TQueryHelpers = {}>(
388
- name: string,
389
- schema?: Schema<T, U, TQueryHelpers>,
390
- collection?: string,
391
- options?: CompileModelOptions
392
- ): U;
393
-
394
- /** Returns an array of model names created on this connection. */
395
- modelNames(): Array<string>;
396
-
397
- /** The name of the database this connection points to. */
398
- name: string;
399
-
400
- /** Opens the connection with a URI using `MongoClient.connect()`. */
401
- openUri(uri: string, options?: ConnectOptions): Promise<Connection>;
402
- openUri(uri: string, callback: (err: CallbackError, conn?: Connection) => void): Connection;
403
- openUri(uri: string, options: ConnectOptions, callback: (err: CallbackError, conn?: Connection) => void): Connection;
404
-
405
- /** The password specified in the URI */
406
- pass: string;
407
-
408
- /**
409
- * The port portion of the URI. If multiple hosts, such as a replica set,
410
- * this will contain the port from the first host name in the URI.
411
- */
412
- port: number;
413
-
414
- /** Declares a plugin executed on all schemas you pass to `conn.model()` */
415
- plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Connection;
416
-
417
- /** The plugins that will be applied to all models created on this connection. */
418
- plugins: Array<any>;
419
-
420
- /**
421
- * Connection ready state
422
- *
423
- * - 0 = disconnected
424
- * - 1 = connected
425
- * - 2 = connecting
426
- * - 3 = disconnecting
427
- */
428
- readyState: number;
429
-
430
- /** Sets the value of the option `key`. Equivalent to `conn.options[key] = val` */
431
- set(key: string, value: any): any;
432
-
433
- /**
434
- * Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
435
- * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
436
- * reuse it.
437
- */
438
- setClient(client: mongodb.MongoClient): this;
439
-
440
- /**
441
- * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
442
- * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
443
- * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
444
- */
445
- startSession(options?: mongodb.ClientSessionOptions): Promise<mongodb.ClientSession>;
446
- startSession(options: mongodb.ClientSessionOptions, cb: Callback<mongodb.ClientSession>): void;
447
-
448
- /**
449
- * Makes the indexes in MongoDB match the indexes defined in every model's
450
- * schema. This function will drop any indexes that are not defined in
451
- * the model's schema except the `_id` index, and build any indexes that
452
- * are in your schema but not in MongoDB.
453
- */
454
- syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
455
- syncIndexes(options: SyncIndexesOptions | null, callback: Callback<ConnectionSyncIndexesResult>): void;
456
-
457
- /**
458
- * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
459
- * in a transaction. Mongoose will commit the transaction if the
460
- * async function executes successfully and attempt to retry if
461
- * there was a retryable error.
462
- */
463
- transaction(fn: (session: mongodb.ClientSession) => Promise<any>): Promise<any>;
464
-
465
- /** Switches to a different database using the same connection pool. */
466
- useDb(name: string, options?: { useCache?: boolean, noListener?: boolean }): Connection;
467
-
468
- /** The username specified in the URI */
469
- user: string;
470
-
471
- /** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model.watch). */
472
- watch<ResultType = any>(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
473
- }
474
-
475
282
  /*
476
283
  * section collection.js
477
284
  * http://mongoosejs.com/docs/api.html#collection-js
@@ -981,7 +788,7 @@ declare module 'mongoose' {
981
788
  translateAliases(raw: any): any;
982
789
 
983
790
  /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
984
- distinct(field: string, filter?: FilterQuery<T>, callback?: Callback<number>): QueryWithHelpers<Array<any>, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
791
+ distinct<ReturnType = any>(field: string, filter?: FilterQuery<T>, callback?: Callback<number>): QueryWithHelpers<Array<ReturnType>, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
985
792
 
986
793
  /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
987
794
  estimatedDocumentCount(options?: QueryOptions, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
@@ -1309,6 +1116,9 @@ declare module 'mongoose' {
1309
1116
  /** Returns a copy of this schema */
1310
1117
  clone<T = this>(): T;
1311
1118
 
1119
+ /** Returns a new schema that has the picked `paths` from this schema. */
1120
+ pick<T = this>(paths: string[], options?: SchemaOptions): T;
1121
+
1312
1122
  /** Object containing discriminators defined on this schema */
1313
1123
  discriminators?: { [name: string]: Schema };
1314
1124
 
@@ -1628,6 +1438,7 @@ declare module 'mongoose' {
1628
1438
  T extends ReadonlyArray<infer U> ? U : T;
1629
1439
 
1630
1440
  type AnyArray<T> = T[] | ReadonlyArray<T>;
1441
+ type SchemaValidator<T> = RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
1631
1442
 
1632
1443
  export class SchemaTypeOptions<T> {
1633
1444
  type?:
@@ -1650,7 +1461,7 @@ declare module 'mongoose' {
1650
1461
  alias?: string;
1651
1462
 
1652
1463
  /** Function or object describing how to validate this schematype. See [validation docs](https://mongoosejs.com/docs/validation.html). */
1653
- validate?: RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
1464
+ validate?: SchemaValidator<T> | AnyArray<SchemaValidator<T>>;
1654
1465
 
1655
1466
  /** Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message. */
1656
1467
  cast?: string;
@@ -2263,7 +2074,7 @@ declare module 'mongoose' {
2263
2074
  deleteOne(callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
2264
2075
 
2265
2076
  /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
2266
- distinct(field: string, filter?: FilterQuery<DocType>, callback?: Callback<number>): QueryWithHelpers<Array<any>, DocType, THelpers, RawDocType>;
2077
+ distinct<ReturnType = any>(field: string, filter?: FilterQuery<DocType>, callback?: Callback<number>): QueryWithHelpers<Array<ReturnType>, DocType, THelpers, RawDocType>;
2267
2078
 
2268
2079
  /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
2269
2080
  elemMatch(val: Function | any): this;
@@ -2676,6 +2487,13 @@ declare module 'mongoose' {
2676
2487
  } &
2677
2488
  RootQuerySelector<T>;
2678
2489
 
2490
+ /**
2491
+ * Filter query to select the documents that match the query
2492
+ * @example
2493
+ * ```js
2494
+ * { age: { $gte: 30 } }
2495
+ * ```
2496
+ */
2679
2497
  export type FilterQuery<T> = _FilterQuery<T>;
2680
2498
 
2681
2499
  type AddToSetOperators<Type> = {
@@ -2733,6 +2551,13 @@ declare module 'mongoose' {
2733
2551
  [K in keyof T]?: __UpdateDefProperty<T[K]>;
2734
2552
  };
2735
2553
 
2554
+ /**
2555
+ * Update query command to perform on the document
2556
+ * @example
2557
+ * ```js
2558
+ * { age: 30 }
2559
+ * ```
2560
+ */
2736
2561
  export type UpdateQuery<T> = _UpdateQuery<_UpdateQueryDef<T>> & AnyObject;
2737
2562
 
2738
2563
  export type DocumentDefinition<T> = {
@@ -2775,6 +2600,12 @@ declare module 'mongoose' {
2775
2600
  T;
2776
2601
 
2777
2602
  export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
2603
+
2604
+ /**
2605
+ * Documents returned from queries with the lean option enabled.
2606
+ * Plain old JavaScript object documents (POJO).
2607
+ * @see https://mongoosejs.com/docs/tutorials/lean.html
2608
+ */
2778
2609
  export type LeanDocument<T> = Omit<_LeanDocument<T>, Exclude<keyof Document, '_id' | 'id' | '__v'> | '$isSingleNested'>;
2779
2610
 
2780
2611
  export type LeanDocumentOrArray<T> = 0 extends (1 & T) ? T :