mongoose 6.3.3 → 6.3.6

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 (47) hide show
  1. package/.eslintrc.json +1 -1
  2. package/dist/browser.umd.js +1 -1
  3. package/lgtm.yml +12 -0
  4. package/lib/cast/objectid.js +3 -2
  5. package/lib/connection.js +3 -2
  6. package/lib/document.js +15 -8
  7. package/lib/error/index.js +2 -2
  8. package/lib/helpers/clone.js +9 -2
  9. package/lib/helpers/common.js +3 -4
  10. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +2 -2
  11. package/lib/helpers/isBsonType.js +5 -3
  12. package/lib/helpers/path/setDottedPath.js +14 -1
  13. package/lib/helpers/topology/isAtlas.js +15 -2
  14. package/lib/helpers/update/applyTimestampsToChildren.js +4 -0
  15. package/lib/index.js +4 -3
  16. package/lib/model.js +38 -54
  17. package/lib/query.js +4 -1
  18. package/lib/queryhelpers.js +3 -2
  19. package/lib/schema/decimal128.js +4 -4
  20. package/lib/schema/map.js +8 -0
  21. package/lib/schema/objectid.js +4 -3
  22. package/lib/schema/string.js +2 -2
  23. package/lib/schema.js +41 -2
  24. package/lib/types/DocumentArray/methods/index.js +3 -3
  25. package/lib/types/array/methods/index.js +3 -3
  26. package/lib/types/map.js +4 -4
  27. package/lib/utils.js +3 -4
  28. package/package.json +18 -16
  29. package/types/aggregate.d.ts +3 -4
  30. package/types/callback.d.ts +8 -0
  31. package/types/collection.d.ts +46 -0
  32. package/types/connection.d.ts +92 -72
  33. package/types/document.d.ts +1 -1
  34. package/types/error.d.ts +5 -1
  35. package/types/helpers.d.ts +33 -0
  36. package/types/index.d.ts +32 -1859
  37. package/types/indizes.d.ts +98 -0
  38. package/types/middlewares.d.ts +14 -0
  39. package/types/models.d.ts +419 -0
  40. package/types/populate.d.ts +40 -0
  41. package/types/query.d.ts +637 -0
  42. package/types/schematypes.d.ts +418 -0
  43. package/types/session.d.ts +36 -0
  44. package/types/types.d.ts +102 -0
  45. package/types/utility.d.ts +13 -0
  46. package/types/validation.d.ts +32 -0
  47. package/.lgtm.yml +0 -3
package/lib/schema.js CHANGED
@@ -473,9 +473,39 @@ Schema.prototype.defaultOptions = function(options) {
473
473
  return options;
474
474
  };
475
475
 
476
+ /**
477
+ * Inherit a Schema by applying a discriminator on an existing Schema.
478
+ *
479
+ *
480
+ * ####Example:
481
+ *
482
+ * const options = { discriminatorKey: 'kind' };
483
+ *
484
+ * const eventSchema = new mongoose.Schema({ time: Date }, options);
485
+ * const Event = mongoose.model('Event', eventSchema);
486
+ *
487
+ * // ClickedLinkEvent is a special type of Event that has
488
+ * // a URL.
489
+ * const ClickedLinkEvent = Event.discriminator('ClickedLink',
490
+ * new mongoose.Schema({ url: String }, options));
491
+ *
492
+ * // When you create a generic event, it can't have a URL field...
493
+ * const genericEvent = new Event({ time: Date.now(), url: 'google.com' });
494
+ * assert.ok(!genericEvent.url);
495
+ * // But a ClickedLinkEvent can
496
+ * const clickedEvent = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
497
+ * assert.ok(clickedEvent.url);
498
+ *
499
+ * @param {String} name the name of the discriminator
500
+ * @param {Schema} schema the Schema of the discriminated Schema
501
+ * @return {Schema} the Schema instance
502
+ * @api public
503
+ */
504
+
476
505
  Schema.prototype.discriminator = function(name, schema) {
477
- this._applyDiscriminators = {};
478
- this._applyDiscriminators[name] = schema;
506
+ this._applyDiscriminators = Object.assign(this._applyDiscriminators || {}, { [name]: schema });
507
+
508
+ return this;
479
509
  };
480
510
 
481
511
  /**
@@ -1235,6 +1265,15 @@ function createMapNestedSchemaType(schema, schemaType, path, obj, options) {
1235
1265
  _mapType = { [schema.options.typeKey]: obj.of };
1236
1266
  }
1237
1267
 
1268
+ if (_mapType[schema.options.typeKey] && _mapType[schema.options.typeKey].instanceOfSchema) {
1269
+ const subdocumentSchema = _mapType[schema.options.typeKey];
1270
+ subdocumentSchema.eachPath((subpath, type) => {
1271
+ if (type.options.select === true || type.options.select === false) {
1272
+ throw new MongooseError('Cannot use schema-level projections (`select: true` or `select: false`) within maps at path "' + path + '.' + subpath + '"');
1273
+ }
1274
+ });
1275
+ }
1276
+
1238
1277
  if (utils.hasUserDefinedProperty(obj, 'ref')) {
1239
1278
  _mapType.ref = obj.ref;
1240
1279
  }
@@ -2,11 +2,11 @@
2
2
 
3
3
  const ArrayMethods = require('../../array/methods');
4
4
  const Document = require('../../../document');
5
- const ObjectId = require('../../objectid');
6
5
  const castObjectId = require('../../../cast/objectid');
7
6
  const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue');
8
7
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
9
8
  const utils = require('../../../utils');
9
+ const isBsonType = require('../../../helpers/isBsonType');
10
10
 
11
11
  const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol;
12
12
  const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol;
@@ -66,7 +66,7 @@ const methods = {
66
66
  // only objects are permitted so we can safely assume that
67
67
  // non-objects are to be interpreted as _id
68
68
  if (Buffer.isBuffer(value) ||
69
- value instanceof ObjectId || !utils.isObject(value)) {
69
+ isBsonType(value, 'ObjectID') || !utils.isObject(value)) {
70
70
  value = { _id: value };
71
71
  }
72
72
 
@@ -134,7 +134,7 @@ const methods = {
134
134
  if (sid == _id._id) {
135
135
  return val;
136
136
  }
137
- } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) {
137
+ } else if (!isBsonType(id, 'ObjectID') && !isBsonType(_id, 'ObjectID')) {
138
138
  if (id == _id || utils.deepEqual(id, _id)) {
139
139
  return val;
140
140
  }
@@ -3,10 +3,10 @@
3
3
  const Document = require('../../../document');
4
4
  const ArraySubdocument = require('../../ArraySubdocument');
5
5
  const MongooseError = require('../../../error/mongooseError');
6
- const ObjectId = require('../../objectid');
7
6
  const cleanModifiedSubpaths = require('../../../helpers/document/cleanModifiedSubpaths');
8
7
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
9
8
  const utils = require('../../../utils');
9
+ const isBsonType = require('../../../helpers/isBsonType');
10
10
 
11
11
  const arrayAtomicsSymbol = require('../../../helpers/symbols').arrayAtomicsSymbol;
12
12
  const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol;
@@ -227,7 +227,7 @@ const methods = {
227
227
  // only objects are permitted so we can safely assume that
228
228
  // non-objects are to be interpreted as _id
229
229
  if (Buffer.isBuffer(value) ||
230
- value instanceof ObjectId || !utils.isObject(value)) {
230
+ isBsonType(value, 'ObjectID') || !utils.isObject(value)) {
231
231
  value = { _id: value };
232
232
  }
233
233
 
@@ -469,7 +469,7 @@ const methods = {
469
469
  */
470
470
 
471
471
  indexOf(obj, fromIndex) {
472
- if (obj instanceof ObjectId) {
472
+ if (isBsonType(obj, 'ObjectID')) {
473
473
  obj = obj.toString();
474
474
  }
475
475
 
package/lib/types/map.js CHANGED
@@ -1,13 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  const Mixed = require('../schema/mixed');
4
- const ObjectId = require('./objectid');
5
4
  const clone = require('../helpers/clone');
6
5
  const deepEqual = require('../utils').deepEqual;
7
6
  const getConstructorName = require('../helpers/getConstructorName');
8
7
  const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
9
8
  const util = require('util');
10
9
  const specialProperties = require('../helpers/specialProperties');
10
+ const isBsonType = require('../helpers/isBsonType');
11
11
 
12
12
  const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
13
13
 
@@ -43,7 +43,7 @@ class MongooseMap extends Map {
43
43
  }
44
44
 
45
45
  get(key, options) {
46
- if (key instanceof ObjectId) {
46
+ if (isBsonType(key, 'ObjectID')) {
47
47
  key = key.toString();
48
48
  }
49
49
 
@@ -55,7 +55,7 @@ class MongooseMap extends Map {
55
55
  }
56
56
 
57
57
  set(key, value) {
58
- if (key instanceof ObjectId) {
58
+ if (isBsonType(key, 'ObjectID')) {
59
59
  key = key.toString();
60
60
  }
61
61
 
@@ -117,7 +117,7 @@ class MongooseMap extends Map {
117
117
  }
118
118
 
119
119
  delete(key) {
120
- if (key instanceof ObjectId) {
120
+ if (isBsonType(key, 'ObjectID')) {
121
121
  key = key.toString();
122
122
  }
123
123
 
package/lib/utils.js CHANGED
@@ -6,7 +6,6 @@
6
6
 
7
7
  const ms = require('ms');
8
8
  const mpath = require('mpath');
9
- const Decimal = require('./types/decimal128');
10
9
  const ObjectId = require('./types/objectid');
11
10
  const PopulateOptions = require('./options/PopulateOptions');
12
11
  const clone = require('./helpers/clone');
@@ -307,7 +306,7 @@ exports.merge = function merge(to, from, options, path) {
307
306
  to[key] = from[key].clone();
308
307
  }
309
308
  continue;
310
- } else if (from[key] instanceof ObjectId) {
309
+ } else if (isBsonType(from[key], 'ObjectID')) {
311
310
  to[key] = new ObjectId(from[key]);
312
311
  continue;
313
312
  }
@@ -481,7 +480,7 @@ exports.tick = function tick(callback) {
481
480
  */
482
481
 
483
482
  exports.isMongooseType = function(v) {
484
- return v instanceof ObjectId || v instanceof Decimal || v instanceof Buffer;
483
+ return isBsonType(v, 'ObjectID') || isBsonType(v, 'Decimal128') || v instanceof Buffer;
485
484
  };
486
485
 
487
486
  exports.isMongooseObject = isMongooseObject;
@@ -795,7 +794,7 @@ exports.array.unique = function(arr) {
795
794
  }
796
795
  ret.push(item);
797
796
  primitives.add(item);
798
- } else if (item instanceof ObjectId) {
797
+ } else if (isBsonType(item, 'ObjectID')) {
799
798
  if (ids.has(item.toString())) {
800
799
  continue;
801
800
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "6.3.3",
4
+ "version": "6.3.6",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -23,15 +23,14 @@
23
23
  "kareem": "2.3.5",
24
24
  "mongodb": "4.5.0",
25
25
  "mpath": "0.9.0",
26
- "mquery": "4.0.2",
26
+ "mquery": "4.0.3",
27
27
  "ms": "2.1.3",
28
28
  "sift": "16.0.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@babel/core": "7.17.10",
32
- "@babel/preset-env": "7.17.10",
33
- "@typescript-eslint/eslint-plugin": "5.21.0",
34
- "@typescript-eslint/parser": "5.21.0",
31
+ "@babel/core": "7.18.2",
32
+ "@typescript-eslint/eslint-plugin": "5.27.0",
33
+ "@typescript-eslint/parser": "5.27.0",
35
34
  "acquit": "1.2.1",
36
35
  "acquit-ignore": "0.2.0",
37
36
  "acquit-require": "0.1.1",
@@ -41,30 +40,31 @@
41
40
  "benchmark": "2.1.4",
42
41
  "bluebird": "3.7.2",
43
42
  "buffer": "^5.6.0",
44
- "cheerio": "1.0.0-rc.10",
43
+ "cheerio": "1.0.0-rc.11",
45
44
  "crypto-browserify": "3.12.0",
46
45
  "dox": "0.3.1",
47
- "eslint": "8.14.0",
46
+ "eslint": "8.16.0",
48
47
  "eslint-plugin-mocha-no-only": "1.1.1",
49
48
  "highlight.js": "11.5.1",
50
49
  "lodash.isequal": "4.5.0",
51
50
  "lodash.isequalwith": "4.4.0",
52
- "marked": "4.0.14",
51
+ "marked": "4.0.16",
53
52
  "mkdirp": "^1.0.4",
54
53
  "mocha": "10.0.0",
55
54
  "moment": "2.x",
56
- "mongodb-memory-server": "8.5.2",
55
+ "mongodb-memory-server": "8.6.0",
57
56
  "ncp": "^2.0.0",
58
57
  "nyc": "15.1.0",
59
58
  "pug": "3.0.2",
60
59
  "q": "1.5.1",
61
60
  "serve-handler": "6.1.3",
62
- "sinon": "13.0.2",
61
+ "sinon": "14.0.0",
63
62
  "stream-browserify": "3.0.0",
63
+ "ts-benchmark": "^1.0.2",
64
64
  "tsd": "0.20.0",
65
- "typescript": "4.6.4",
65
+ "typescript": "4.7.2",
66
66
  "uuid": "8.3.2",
67
- "webpack": "5.72.0"
67
+ "webpack": "5.72.1"
68
68
  },
69
69
  "directories": {
70
70
  "lib": "./lib/mongoose"
@@ -83,8 +83,8 @@
83
83
  "docs:merge:legacy": "git merge 5.x",
84
84
  "docs:test": "npm run docs:generate && npm run docs:generate:search",
85
85
  "docs:view": "node website.js && node static.js",
86
- "docs:prepare:publish:stable": "npm run docs:checkout:gh-pages && docs:merge:stable && npm run docs:clean:stable && npm run docs:generate && npm run docs:generate:search",
87
- "docs:prepare:publish:legacy": "npm run docs:checkout:legacy && docs:merge:legacy && npm run docs:clean:stable && npm run docs:generate && npm run docs:copy:tmp && docs:checkout:gh-pages && docs:copy:tmp:legacy",
86
+ "docs:prepare:publish:stable": "npm run docs:checkout:gh-pages && npm run docs:merge:stable && npm run docs:clean:stable && npm run docs:generate && npm run docs:generate:search",
87
+ "docs:prepare:publish:legacy": "npm run docs:checkout:legacy && npm run docs:merge:legacy && npm run docs:clean:stable && npm run docs:generate && npm run docs:copy:tmp && docs:checkout:gh-pages && docs:copy:tmp:legacy",
88
88
  "lint": "eslint .",
89
89
  "lint-js": "eslint . --ext .js",
90
90
  "lint-ts": "eslint . --ext .ts",
@@ -97,7 +97,9 @@
97
97
  "test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit ./test/*.test.js",
98
98
  "test-tsd": "node ./test/types/check-types-filename && tsd",
99
99
  "tdd": "mocha ./test/*.test.js ./test/typescript/main.test.js --inspect --watch --recursive --watch-files ./**/*.js",
100
- "test-coverage": "nyc --reporter=html --reporter=text npm test"
100
+ "test-coverage": "nyc --reporter=html --reporter=text npm test",
101
+ "ts-benchmark": "ts-benchmark -p ./benchmarks/typescript/simple -f 17 18 29 32",
102
+ "ts-benchmark-watch": "ts-benchmark -p ./benchmarks/typescript/simple -w ./types -i -s -f 17 18 29 32 -b master"
101
103
  },
102
104
  "main": "./index.js",
103
105
  "types": "./types/index.d.ts",
@@ -1,7 +1,8 @@
1
1
  declare module 'mongoose' {
2
2
  import mongodb = require('mongodb');
3
3
 
4
- interface AggregateOptions {
4
+ interface AggregateOptions extends
5
+ SessionOption {
5
6
  /**
6
7
  * If true, the MongoDB server will use the hard drive to store data during this aggregation.
7
8
  */
@@ -56,8 +57,6 @@ declare module 'mongoose' {
56
57
  * The preferred read preference.
57
58
  */
58
59
  readPreference?: mongodb.ReadPreferenceLike;
59
- /** The ClientSession for this aggregation */
60
- session?: mongodb.ClientSession;
61
60
  /**
62
61
  * Specifies the write concern.
63
62
  */
@@ -65,7 +64,7 @@ declare module 'mongoose' {
65
64
  [key: string]: any;
66
65
  }
67
66
 
68
- class Aggregate<R> {
67
+ class Aggregate<R> implements SessionOperation {
69
68
  /**
70
69
  * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js
71
70
  * You do not need to call this function explicitly, the JavaScript runtime
@@ -0,0 +1,8 @@
1
+ declare module 'mongoose' {
2
+ type CallbackError = NativeError | null;
3
+
4
+ type Callback<T = any> = (error: CallbackError, result: T) => void;
5
+
6
+ type CallbackWithoutResult = (error: CallbackError) => void;
7
+ type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
8
+ }
@@ -0,0 +1,46 @@
1
+ declare module 'mongoose' {
2
+ import mongodb = require('mongodb');
3
+
4
+ /*
5
+ * section collection.js
6
+ * http://mongoosejs.com/docs/api.html#collection-js
7
+ */
8
+ interface CollectionBase<T extends mongodb.Document> extends mongodb.Collection<T> {
9
+ /*
10
+ * Abstract methods. Some of these are already defined on the
11
+ * mongodb.Collection interface so they've been commented out.
12
+ */
13
+ ensureIndex(...args: any[]): any;
14
+ findAndModify(...args: any[]): any;
15
+ getIndexes(...args: any[]): any;
16
+
17
+ /** The collection name */
18
+ collectionName: string;
19
+ /** The Connection instance */
20
+ conn: Connection;
21
+ /** The collection name */
22
+ name: string;
23
+ }
24
+
25
+ /*
26
+ * section drivers/node-mongodb-native/collection.js
27
+ * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js
28
+ */
29
+ interface Collection<T extends mongodb.Document = mongodb.Document> extends CollectionBase<T> {
30
+ /**
31
+ * Collection constructor
32
+ * @param name name of the collection
33
+ * @param conn A MongooseConnection instance
34
+ * @param opts optional collection options
35
+ */
36
+ // eslint-disable-next-line @typescript-eslint/no-misused-new
37
+ new(name: string, conn: Connection, opts?: any): Collection<T>;
38
+ /** Formatter for debug print args */
39
+ $format(arg: any, color?: boolean, shell?: boolean): string;
40
+ /** Debug print helper */
41
+ $print(name: string, i: string | number, args: any[], color?: boolean, shell?: boolean): void;
42
+ /** Retrieves information about this collections indexes. */
43
+ getIndexes(): ReturnType<mongodb.Collection<T>['indexInformation']>;
44
+ }
45
+ let Collection: Collection;
46
+ }
@@ -2,16 +2,36 @@ declare module 'mongoose' {
2
2
  import mongodb = require('mongodb');
3
3
  import events = require('events');
4
4
 
5
+ /** The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). */
6
+ const connection: Connection;
7
+
8
+ /** An array containing all connections associated with this Mongoose instance. */
9
+ const connections: Connection[];
10
+
11
+ /** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
12
+ function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
13
+ function connect(uri: string, callback: CallbackWithoutResult): void;
14
+ function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;
15
+
16
+ /** Creates a Connection instance. */
17
+ function createConnection(uri: string, options: ConnectOptions, callback: Callback<Connection>): void;
18
+ function createConnection(uri: string, callback: Callback<Connection>): void;
19
+ function createConnection(uri: string, options?: ConnectOptions): Connection;
20
+ function createConnection(): Connection;
21
+
22
+ function disconnect(callback: CallbackWithoutResult): void;
23
+ function disconnect(): Promise<void>;
24
+
5
25
  /**
6
- * Connection ready state
7
- *
8
- * - 0 = disconnected
9
- * - 1 = connected
10
- * - 2 = connecting
11
- * - 3 = disconnecting
12
- * - 99 = uninitialized
13
- */
14
- export enum ConnectionStates {
26
+ * Connection ready state
27
+ *
28
+ * - 0 = disconnected
29
+ * - 1 = connected
30
+ * - 2 = connecting
31
+ * - 3 = disconnecting
32
+ * - 99 = uninitialized
33
+ */
34
+ enum ConnectionStates {
15
35
  disconnected = 0,
16
36
  connected = 1,
17
37
  connecting = 2,
@@ -20,7 +40,7 @@ declare module 'mongoose' {
20
40
  }
21
41
 
22
42
  /** Expose connection states for user-land */
23
- export const STATES: typeof ConnectionStates;
43
+ const STATES: typeof ConnectionStates;
24
44
 
25
45
  interface ConnectOptions extends mongodb.MongoClientOptions {
26
46
  /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
@@ -37,7 +57,7 @@ declare module 'mongoose' {
37
57
  autoCreate?: boolean;
38
58
  }
39
59
 
40
- class Connection extends events.EventEmitter {
60
+ class Connection extends events.EventEmitter implements SessionStarter {
41
61
  /** Returns a promise that resolves when this connection successfully connects to MongoDB */
42
62
  asPromise(): Promise<this>;
43
63
 
@@ -59,32 +79,32 @@ declare module 'mongoose' {
59
79
  readonly db: mongodb.Db;
60
80
 
61
81
  /**
62
- * Helper for `createCollection()`. Will explicitly create the given collection
63
- * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/)
64
- * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
65
- */
82
+ * Helper for `createCollection()`. Will explicitly create the given collection
83
+ * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/)
84
+ * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose.
85
+ */
66
86
  createCollection<T extends AnyObject = AnyObject>(name: string, options: mongodb.CreateCollectionOptions, callback: Callback<mongodb.Collection<T>>): void;
67
87
  createCollection<T extends AnyObject = AnyObject>(name: string, callback: Callback<mongodb.Collection<T>>): void;
68
88
  createCollection<T extends AnyObject = AnyObject>(name: string, options?: mongodb.CreateCollectionOptions): Promise<mongodb.Collection<T>>;
69
89
 
70
90
  /**
71
- * Removes the model named `name` from this connection, if it exists. You can
72
- * use this function to clean up any models you created in your tests to
73
- * prevent OverwriteModelErrors.
74
- */
75
- deleteModel(name: string): this;
91
+ * Removes the model named `name` from this connection, if it exists. You can
92
+ * use this function to clean up any models you created in your tests to
93
+ * prevent OverwriteModelErrors.
94
+ */
95
+ deleteModel(name: string | RegExp): this;
76
96
 
77
97
  /**
78
- * Helper for `dropCollection()`. Will delete the given collection, including
79
- * all documents and indexes.
80
- */
98
+ * Helper for `dropCollection()`. Will delete the given collection, including
99
+ * all documents and indexes.
100
+ */
81
101
  dropCollection(collection: string, callback: CallbackWithoutResult): void;
82
102
  dropCollection(collection: string): Promise<void>;
83
103
 
84
104
  /**
85
- * Helper for `dropDatabase()`. Deletes the given database, including all
86
- * collections, documents, and indexes.
87
- */
105
+ * Helper for `dropDatabase()`. Deletes the given database, including all
106
+ * collections, documents, and indexes.
107
+ */
88
108
  dropDatabase(callback: CallbackWithoutResult): void;
89
109
  dropDatabase(): Promise<void>;
90
110
 
@@ -92,28 +112,28 @@ declare module 'mongoose' {
92
112
  get(key: string): any;
93
113
 
94
114
  /**
95
- * Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
96
- * that this connection uses to talk to MongoDB.
97
- */
115
+ * Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
116
+ * that this connection uses to talk to MongoDB.
117
+ */
98
118
  getClient(): mongodb.MongoClient;
99
119
 
100
120
  /**
101
- * The host name portion of the URI. If multiple hosts, such as a replica set,
102
- * this will contain the first host name in the URI
103
- */
121
+ * The host name portion of the URI. If multiple hosts, such as a replica set,
122
+ * this will contain the first host name in the URI
123
+ */
104
124
  readonly host: string;
105
125
 
106
126
  /**
107
- * A number identifier for this connection. Used for debugging when
108
- * you have [multiple connections](/docs/connections.html#multiple_connections).
109
- */
127
+ * A number identifier for this connection. Used for debugging when
128
+ * you have [multiple connections](/docs/connections.html#multiple_connections).
129
+ */
110
130
  readonly id: number;
111
131
 
112
132
  /**
113
- * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
114
- * a map from model names to models. Contains all models that have been
115
- * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model).
116
- */
133
+ * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
134
+ * a map from model names to models. Contains all models that have been
135
+ * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model).
136
+ */
117
137
  readonly models: Readonly<{ [index: string]: Model<any> }>;
118
138
 
119
139
  /** Defines or retrieves a model. */
@@ -140,9 +160,9 @@ declare module 'mongoose' {
140
160
  readonly pass: string;
141
161
 
142
162
  /**
143
- * The port portion of the URI. If multiple hosts, such as a replica set,
144
- * this will contain the port from the first host name in the URI.
145
- */
163
+ * The port portion of the URI. If multiple hosts, such as a replica set,
164
+ * this will contain the port from the first host name in the URI.
165
+ */
146
166
  readonly port: number;
147
167
 
148
168
  /** Declares a plugin executed on all schemas you pass to `conn.model()` */
@@ -152,51 +172,51 @@ declare module 'mongoose' {
152
172
  plugins: Array<any>;
153
173
 
154
174
  /**
155
- * Connection ready state
156
- *
157
- * - 0 = disconnected
158
- * - 1 = connected
159
- * - 2 = connecting
160
- * - 3 = disconnecting
161
- * - 99 = uninitialized
162
- */
175
+ * Connection ready state
176
+ *
177
+ * - 0 = disconnected
178
+ * - 1 = connected
179
+ * - 2 = connecting
180
+ * - 3 = disconnecting
181
+ * - 99 = uninitialized
182
+ */
163
183
  readonly readyState: ConnectionStates;
164
184
 
165
185
  /** Sets the value of the option `key`. */
166
186
  set(key: string, value: any): any;
167
187
 
168
188
  /**
169
- * Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
170
- * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
171
- * reuse it.
172
- */
189
+ * Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance
190
+ * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
191
+ * reuse it.
192
+ */
173
193
  setClient(client: mongodb.MongoClient): this;
174
194
 
175
195
  /**
176
- * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
177
- * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
178
- * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
179
- */
180
- startSession(options: mongodb.ClientSessionOptions | undefined | null, callback: Callback<mongodb.ClientSession>): void;
181
- startSession(callback: Callback<mongodb.ClientSession>): void;
182
- startSession(options?: mongodb.ClientSessionOptions): Promise<mongodb.ClientSession>;
196
+ * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
197
+ * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
198
+ * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
199
+ */
200
+ startSession(options: ClientSessionOptions | undefined | null, callback: Callback<ClientSession>): void;
201
+ startSession(callback: Callback<ClientSession>): void;
202
+ startSession(options?: ClientSessionOptions): Promise<ClientSession>;
183
203
 
184
204
  /**
185
- * Makes the indexes in MongoDB match the indexes defined in every model's
186
- * schema. This function will drop any indexes that are not defined in
187
- * the model's schema except the `_id` index, and build any indexes that
188
- * are in your schema but not in MongoDB.
189
- */
205
+ * Makes the indexes in MongoDB match the indexes defined in every model's
206
+ * schema. This function will drop any indexes that are not defined in
207
+ * the model's schema except the `_id` index, and build any indexes that
208
+ * are in your schema but not in MongoDB.
209
+ */
190
210
  syncIndexes(options: SyncIndexesOptions | undefined | null, callback: Callback<ConnectionSyncIndexesResult>): void;
191
211
  syncIndexes(options?: SyncIndexesOptions): Promise<ConnectionSyncIndexesResult>;
192
212
 
193
213
  /**
194
- * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
195
- * in a transaction. Mongoose will commit the transaction if the
196
- * async function executes successfully and attempt to retry if
197
- * there was a retryable error.
198
- */
199
- transaction(fn: (session: mongodb.ClientSession) => Promise<any>): Promise<void>;
214
+ * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
215
+ * in a transaction. Mongoose will commit the transaction if the
216
+ * async function executes successfully and attempt to retry if
217
+ * there was a retryable error.
218
+ */
219
+ transaction(fn: (session: mongodb.ClientSession) => Promise<any>, options?: mongodb.TransactionOptions): Promise<void>;
200
220
 
201
221
  /** Switches to a different database using the same connection pool. */
202
222
  useDb(name: string, options?: { useCache?: boolean, noListener?: boolean }): Connection;
@@ -68,7 +68,7 @@ declare module 'mongoose' {
68
68
  * automatically set `session` if you `save()` a doc that you got from a
69
69
  * query with an associated session.
70
70
  */
71
- $session(session?: mongodb.ClientSession | null): mongodb.ClientSession | null;
71
+ $session(session?: ClientSession | null): ClientSession | null;
72
72
 
73
73
  /** Alias for `set()`, used internally to avoid conflicts */
74
74
  $set(path: string, val: any, type: any, options?: any): this;
package/types/error.d.ts CHANGED
@@ -3,7 +3,8 @@ declare class NativeError extends global.Error { }
3
3
  declare module 'mongoose' {
4
4
  import mongodb = require('mongodb');
5
5
 
6
- type CallbackError = NativeError | null;
6
+ type CastError = Error.CastError;
7
+ type SyncIndexesError = Error.SyncIndexesError;
7
8
 
8
9
  class MongooseError extends global.Error {
9
10
  constructor(msg: string);
@@ -16,7 +17,10 @@ declare module 'mongoose' {
16
17
  static Messages: any;
17
18
  }
18
19
 
20
+ class Error extends MongooseError { }
21
+
19
22
  namespace Error {
23
+
20
24
  export class CastError extends MongooseError {
21
25
  name: 'CastError';
22
26
  stringValue: string;