mongoose 6.3.0 → 6.3.3

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 (42) hide show
  1. package/.eslintrc.json +157 -157
  2. package/README.md +2 -2
  3. package/dist/browser.umd.js +1 -1
  4. package/lib/collection.js +0 -7
  5. package/lib/connection.js +2 -1
  6. package/lib/document.js +65 -68
  7. package/lib/error/cast.js +8 -2
  8. package/lib/helpers/common.js +0 -8
  9. package/lib/helpers/immediate.js +3 -1
  10. package/lib/helpers/isAsyncFunction.js +19 -7
  11. package/lib/helpers/model/castBulkWrite.js +12 -0
  12. package/lib/helpers/populate/getModelsMapForPopulate.js +13 -10
  13. package/lib/helpers/query/cast$expr.js +4 -1
  14. package/lib/helpers/schematype/handleImmutable.js +4 -1
  15. package/lib/helpers/timestamps/setupTimestamps.js +2 -2
  16. package/lib/index.js +1 -1
  17. package/lib/internal.js +0 -1
  18. package/lib/model.js +42 -28
  19. package/lib/query.js +7 -3
  20. package/lib/queryhelpers.js +11 -1
  21. package/lib/schema/SubdocumentPath.js +3 -15
  22. package/lib/schema/documentarray.js +7 -7
  23. package/lib/schema/number.js +1 -5
  24. package/lib/schema/objectid.js +2 -4
  25. package/lib/schema/string.js +3 -6
  26. package/lib/schema.js +1 -1
  27. package/lib/schematype.js +2 -2
  28. package/lib/types/DocumentArray/methods/index.js +9 -1
  29. package/lib/types/array/methods/index.js +8 -9
  30. package/lib/utils.js +4 -0
  31. package/package.json +39 -19
  32. package/tsconfig.json +2 -2
  33. package/types/aggregate.d.ts +1 -2
  34. package/types/connection.d.ts +4 -5
  35. package/types/cursor.d.ts +3 -2
  36. package/types/document.d.ts +18 -15
  37. package/types/error.d.ts +124 -124
  38. package/types/index.d.ts +182 -154
  39. package/types/mongooseoptions.d.ts +1 -2
  40. package/types/schemaoptions.d.ts +1 -2
  41. package/CHANGELOG.md +0 -7249
  42. package/History.md +0 -1
@@ -261,7 +261,17 @@ exports.applyPaths = function applyPaths(fields, schema) {
261
261
  delete fields[plusPath];
262
262
  }
263
263
 
264
- if (typeof type.selected !== 'boolean') return;
264
+ if (typeof type.selected !== 'boolean') {
265
+ return;
266
+ }
267
+
268
+ // If set to 0, we're explicitly excluding the discriminator key. Can't do this for all fields,
269
+ // because we have tests that assert that using `-path` to exclude schema-level `select: true`
270
+ // fields counts as an exclusive projection. See gh-11546
271
+ if (exclude && type.selected && path === schema.options.discriminatorKey && fields[path] != null && !fields[path]) {
272
+ delete fields[path];
273
+ return;
274
+ }
265
275
 
266
276
  if (hasPlusPath) {
267
277
  // forced inclusion
@@ -60,25 +60,13 @@ function _createConstructor(schema, baseClass) {
60
60
  Subdocument || (Subdocument = require('../types/subdocument'));
61
61
 
62
62
  const _embedded = function SingleNested(value, path, parent) {
63
- const _this = this;
64
-
65
63
  this.$__parent = parent;
66
64
  Subdocument.apply(this, arguments);
67
65
 
68
- this.$session(this.ownerDocument().$session());
69
-
70
- if (parent) {
71
- parent.$on('save', function() {
72
- _this.emit('save', _this);
73
- _this.constructor.emit('save', _this);
74
- });
75
-
76
- parent.$on('isNew', function(val) {
77
- _this.isNew = val;
78
- _this.emit('isNew', val);
79
- _this.constructor.emit('isNew', val);
80
- });
66
+ if (parent == null) {
67
+ return;
81
68
  }
69
+ this.$session(parent.$session());
82
70
  };
83
71
 
84
72
  schema._preCompile();
@@ -13,7 +13,6 @@ const SchemaType = require('../schematype');
13
13
  const discriminator = require('../helpers/model/discriminator');
14
14
  const handleIdOption = require('../helpers/schema/handleIdOption');
15
15
  const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
16
- const util = require('util');
17
16
  const utils = require('../utils');
18
17
  const getConstructor = require('../helpers/discriminator/getConstructor');
19
18
 
@@ -114,10 +113,12 @@ function _createConstructor(schema, options, baseClass) {
114
113
  Subdocument || (Subdocument = require('../types/ArraySubdocument'));
115
114
 
116
115
  // compile an embedded document for this schema
117
- function EmbeddedDocument() {
116
+ function EmbeddedDocument(_value, parentArray) {
118
117
  Subdocument.apply(this, arguments);
119
-
120
- this.$session(this.ownerDocument().$session());
118
+ if (parentArray == null || parentArray.getArrayParent() == null) {
119
+ return;
120
+ }
121
+ this.$session(parentArray.getArrayParent().$session());
121
122
  }
122
123
 
123
124
  schema._preCompile();
@@ -394,7 +395,7 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
394
395
 
395
396
  if (!Array.isArray(value)) {
396
397
  if (!init && !DocumentArrayPath.options.castNonArrays) {
397
- throw new CastError('DocumentArray', util.inspect(value), this.path, null, this);
398
+ throw new CastError('DocumentArray', value, this.path, null, this);
398
399
  }
399
400
  // gh-2442 mark whole array as modified if we're initializing a doc from
400
401
  // the db and the path isn't an array in the document
@@ -486,8 +487,7 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
486
487
  // see gh-746
487
488
  rawArray[i] = subdoc;
488
489
  } catch (error) {
489
- const valueInErrorMessage = util.inspect(rawArray[i]);
490
- throw new CastError('embedded', valueInErrorMessage,
490
+ throw new CastError('embedded', rawArray[i],
491
491
  value[arrayPathSymbol], error, this);
492
492
  }
493
493
  }
@@ -353,11 +353,7 @@ SchemaNumber.prototype.enum = function(values, message) {
353
353
  */
354
354
 
355
355
  SchemaNumber.prototype.cast = function(value, doc, init) {
356
- if (SchemaType._isRef(this, value, doc, init)) {
357
- if (typeof value === 'number') {
358
- return value;
359
- }
360
-
356
+ if (typeof value !== 'number' && SchemaType._isRef(this, value, doc, init)) {
361
357
  if (value == null || utils.isNonBuiltinObject(value)) {
362
358
  return this._castRef(value, doc, init);
363
359
  }
@@ -221,11 +221,9 @@ ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
221
221
  */
222
222
 
223
223
  ObjectId.prototype.cast = function(value, doc, init) {
224
- if (SchemaType._isRef(this, value, doc, init)) {
224
+ if (!(value instanceof oid) && SchemaType._isRef(this, value, doc, init)) {
225
225
  // wait! we may need to cast this to a document
226
- if (value instanceof oid) {
227
- return value;
228
- } else if ((getConstructorName(value) || '').toLowerCase() === 'objectid') {
226
+ if ((getConstructorName(value) || '').toLowerCase() === 'objectid') {
229
227
  return new oid(value.toHexString());
230
228
  }
231
229
 
@@ -4,6 +4,7 @@
4
4
  * Module dependencies.
5
5
  */
6
6
 
7
+ const { BSONRegExp } = require('bson');
7
8
  const SchemaType = require('../schematype');
8
9
  const MongooseError = require('../error/index');
9
10
  const SchemaStringOptions = require('../options/SchemaStringOptions');
@@ -580,11 +581,7 @@ SchemaString.prototype.checkRequired = function checkRequired(value, doc) {
580
581
  */
581
582
 
582
583
  SchemaString.prototype.cast = function(value, doc, init) {
583
- if (SchemaType._isRef(this, value, doc, init)) {
584
- if (typeof value === 'string') {
585
- return value;
586
- }
587
-
584
+ if (typeof value !== 'string' && SchemaType._isRef(this, value, doc, init)) {
588
585
  return this._castRef(value, doc, init);
589
586
  }
590
587
 
@@ -680,7 +677,7 @@ SchemaString.prototype.castForQuery = function($conditional, val) {
680
677
  return handler.call(this, val);
681
678
  }
682
679
  val = $conditional;
683
- if (Object.prototype.toString.call(val) === '[object RegExp]') {
680
+ if (Object.prototype.toString.call(val) === '[object RegExp]' || val instanceof BSONRegExp) {
684
681
  return val;
685
682
  }
686
683
 
package/lib/schema.js CHANGED
@@ -54,7 +54,7 @@ let id = 0;
54
54
  * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
55
55
  * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true
56
56
  * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out.
57
- * - [capped](/docs/guide.html#capped): bool - defaults to false
57
+ * - [capped](/docs/guide.html#capped): bool | number | object - defaults to false
58
58
  * - [collection](/docs/guide.html#collection): string - no default
59
59
  * - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t`
60
60
  * - [id](/docs/guide.html#id): bool - defaults to true
package/lib/schematype.js CHANGED
@@ -1148,7 +1148,7 @@ SchemaType.prototype.getDefault = function(scope, init) {
1148
1148
  * @api private
1149
1149
  */
1150
1150
 
1151
- SchemaType.prototype._applySetters = function(value, scope, init, priorVal) {
1151
+ SchemaType.prototype._applySetters = function(value, scope, init, priorVal, options) {
1152
1152
  let v = value;
1153
1153
  if (init) {
1154
1154
  return v;
@@ -1156,7 +1156,7 @@ SchemaType.prototype._applySetters = function(value, scope, init, priorVal) {
1156
1156
  const setters = this.setters;
1157
1157
 
1158
1158
  for (let i = setters.length - 1; i >= 0; i--) {
1159
- v = setters[i].call(scope, v, priorVal, this);
1159
+ v = setters[i].call(scope, v, priorVal, this, options);
1160
1160
  }
1161
1161
 
1162
1162
  return v;
@@ -22,6 +22,14 @@ const methods = {
22
22
  return this.toObject(internalToObjectOptions);
23
23
  },
24
24
 
25
+ /*!
26
+ * ignore
27
+ */
28
+
29
+ getArrayParent() {
30
+ return this[arrayParentSymbol];
31
+ },
32
+
25
33
  /**
26
34
  * Overrides MongooseArray#cast
27
35
  *
@@ -311,8 +319,8 @@ const methods = {
311
319
  return this;
312
320
  }
313
321
  const value = methods._cast.call(this, val, i);
314
- arr[i] = value;
315
322
  methods._markModified.call(this, i);
323
+ arr[i] = value;
316
324
  return this;
317
325
  },
318
326
 
@@ -414,9 +414,9 @@ const methods = {
414
414
  }
415
415
 
416
416
  if (!found) {
417
+ this._markModified();
417
418
  rawArray.push(v);
418
419
  this._registerAtomic('$addToSet', v);
419
- this._markModified();
420
420
  [].push.call(added, v);
421
421
  }
422
422
  }, this);
@@ -510,9 +510,9 @@ const methods = {
510
510
 
511
511
  nonAtomicPush() {
512
512
  const values = [].map.call(arguments, this._mapCast, this);
513
+ this._markModified();
513
514
  const ret = [].push.apply(this, values);
514
515
  this._registerAtomic('$set', this);
515
- this._markModified();
516
516
  return ret;
517
517
  },
518
518
 
@@ -530,9 +530,9 @@ const methods = {
530
530
  */
531
531
 
532
532
  pop() {
533
+ this._markModified();
533
534
  const ret = [].pop.call(this);
534
535
  this._registerAtomic('$set', this);
535
- this._markModified();
536
536
  return ret;
537
537
  },
538
538
 
@@ -572,6 +572,7 @@ const methods = {
572
572
  const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]);
573
573
  let i = cur.length;
574
574
  let mem;
575
+ this._markModified();
575
576
 
576
577
  while (i--) {
577
578
  mem = cur[i];
@@ -595,7 +596,6 @@ const methods = {
595
596
  this._registerAtomic('$pullAll', values);
596
597
  }
597
598
 
598
- this._markModified();
599
599
 
600
600
  // Might have modified child paths and then pulled, like
601
601
  // `doc.children[1].name = 'test';` followed by
@@ -657,7 +657,7 @@ const methods = {
657
657
  undefined, { skipDocumentArrayCast: true });
658
658
  let ret;
659
659
  const atomics = this[arrayAtomicsSymbol];
660
-
660
+ this._markModified();
661
661
  if (isOverwrite) {
662
662
  atomic.$each = values;
663
663
 
@@ -684,7 +684,6 @@ const methods = {
684
684
  }
685
685
 
686
686
  this._registerAtomic('$push', atomic);
687
- this._markModified();
688
687
  return ret;
689
688
  },
690
689
 
@@ -737,8 +736,8 @@ const methods = {
737
736
  return this;
738
737
  }
739
738
  const value = methods._cast.call(this, val, i);
740
- arr[i] = value;
741
739
  methods._markModified.call(this, i);
740
+ arr[i] = value;
742
741
  return this;
743
742
  },
744
743
 
@@ -763,9 +762,9 @@ const methods = {
763
762
 
764
763
  shift() {
765
764
  const arr = utils.isMongooseArray(this) ? this.__array : this;
765
+ this._markModified();
766
766
  const ret = [].shift.call(arr);
767
767
  this._registerAtomic('$set', this);
768
- this._markModified();
769
768
  return ret;
770
769
  },
771
770
 
@@ -890,9 +889,9 @@ const methods = {
890
889
  }
891
890
 
892
891
  const arr = utils.isMongooseArray(this) ? this.__array : this;
892
+ this._markModified();
893
893
  [].unshift.apply(arr, values);
894
894
  this._registerAtomic('$set', this);
895
- this._markModified();
896
895
  return this.length;
897
896
  }
898
897
  };
package/lib/utils.js CHANGED
@@ -516,6 +516,10 @@ exports.populate = function populate(path, select, model, match, options, subPop
516
516
  let obj = null;
517
517
  if (arguments.length === 1) {
518
518
  if (path instanceof PopulateOptions) {
519
+ // If reusing old populate docs, avoid reusing `_docs` because that may
520
+ // lead to bugs and memory leaks. See gh-11641
521
+ path._docs = [];
522
+ path._childDocs = [];
519
523
  return [path];
520
524
  }
521
525
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "6.3.0",
4
+ "version": "6.3.3",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -19,54 +19,72 @@
19
19
  ],
20
20
  "license": "MIT",
21
21
  "dependencies": {
22
- "bson": "^4.2.2",
22
+ "bson": "^4.6.2",
23
23
  "kareem": "2.3.5",
24
24
  "mongodb": "4.5.0",
25
- "mpath": "0.8.4",
25
+ "mpath": "0.9.0",
26
26
  "mquery": "4.0.2",
27
27
  "ms": "2.1.3",
28
28
  "sift": "16.0.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@babel/core": "7.17.8",
32
- "@babel/preset-env": "7.16.11",
33
- "@typescript-eslint/eslint-plugin": "5.17.0",
34
- "@typescript-eslint/parser": "5.17.0",
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",
35
35
  "acquit": "1.2.1",
36
36
  "acquit-ignore": "0.2.0",
37
37
  "acquit-require": "0.1.1",
38
- "assert-browserify": "npm:assert@^2.0.0",
39
- "axios": "0.26.1",
40
- "babel-loader": "8.2.4",
38
+ "assert-browserify": "2.0.0",
39
+ "axios": "0.27.2",
40
+ "babel-loader": "8.2.5",
41
41
  "benchmark": "2.1.4",
42
42
  "bluebird": "3.7.2",
43
+ "buffer": "^5.6.0",
43
44
  "cheerio": "1.0.0-rc.10",
44
45
  "crypto-browserify": "3.12.0",
45
46
  "dox": "0.3.1",
46
- "eslint": "8.12.0",
47
+ "eslint": "8.14.0",
47
48
  "eslint-plugin-mocha-no-only": "1.1.1",
48
- "highlight.js": "11.5.0",
49
+ "highlight.js": "11.5.1",
49
50
  "lodash.isequal": "4.5.0",
50
51
  "lodash.isequalwith": "4.4.0",
51
- "marked": "4.0.12",
52
- "mocha": "9.2.2",
52
+ "marked": "4.0.14",
53
+ "mkdirp": "^1.0.4",
54
+ "mocha": "10.0.0",
53
55
  "moment": "2.x",
54
- "mongodb-memory-server": "8.3.0",
56
+ "mongodb-memory-server": "8.5.2",
57
+ "ncp": "^2.0.0",
55
58
  "nyc": "15.1.0",
56
59
  "pug": "3.0.2",
57
60
  "q": "1.5.1",
58
61
  "serve-handler": "6.1.3",
59
- "sinon": "13.0.0",
62
+ "sinon": "13.0.2",
60
63
  "stream-browserify": "3.0.0",
61
- "tsd": "0.19.1",
62
- "typescript": "4.6.3",
64
+ "tsd": "0.20.0",
65
+ "typescript": "4.6.4",
63
66
  "uuid": "8.3.2",
64
- "webpack": "5.70.0"
67
+ "webpack": "5.72.0"
65
68
  },
66
69
  "directories": {
67
70
  "lib": "./lib/mongoose"
68
71
  },
69
72
  "scripts": {
73
+ "docs:clean": "npm run docs:clean:stable",
74
+ "docs:clean:stable": "rimraf index.html && rimraf -rf ./docs/*.html && rimraf -rf ./docs/api && rimraf -rf ./docs/tutorials/*.html && rimraf -rf ./docs/typescript/*.html && rimraf -rf ./docs/*.html && rimraf -rf ./docs/source/_docs && rimraf -rf ./tmp",
75
+ "docs:clean:legacy": "rimraf index.html && rimraf -rf ./docs/5.x && rimraf -rf ./docs/source/_docs && rimraf -rf ./tmp",
76
+ "docs:copy:tmp": "mkdirp ./tmp/docs/css && mkdirp ./tmp/docs/js && mkdirp ./tmp/docs/images && mkdirp ./tmp/docs/tutorials && mkdirp ./tmp/docs/typescript && ncp ./docs/css ./tmp/docs/css --filter=.css$ && ncp ./docs/js ./tmp/docs/js --filter=.js$ && ncp ./docs/images ./tmp/docs/images && ncp ./docs/tutorials ./tmp/docs/tutorials && ncp ./docs/typescript ./tmp/docs/typescript && cp index.html ./tmp",
77
+ "docs:copy:tmp:legacy": "rimraf ./docs/5.x && ncp ./tmp ./docs/5.x",
78
+ "docs:checkout:gh-pages": "git checkout gh-pages",
79
+ "docs:checkout:legacy": "git checkout 5.x",
80
+ "docs:generate": "node website.js",
81
+ "docs:generate:search": "node docs/search.js",
82
+ "docs:merge:stable": "git merge master",
83
+ "docs:merge:legacy": "git merge 5.x",
84
+ "docs:test": "npm run docs:generate && npm run docs:generate:search",
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",
70
88
  "lint": "eslint .",
71
89
  "lint-js": "eslint . --ext .js",
72
90
  "lint-ts": "eslint . --ext .ts",
@@ -76,6 +94,7 @@
76
94
  "release-legacy": "git pull origin 5.x && git push origin 5.x --tags && npm publish --tag legacy",
77
95
  "mongo": "node ./tools/repl.js",
78
96
  "test": "mocha --exit ./test/*.test.js",
97
+ "test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit ./test/*.test.js",
79
98
  "test-tsd": "node ./test/types/check-types-filename && tsd",
80
99
  "tdd": "mocha ./test/*.test.js ./test/typescript/main.test.js --inspect --watch --recursive --watch-files ./**/*.js",
81
100
  "test-coverage": "nyc --reporter=html --reporter=text npm test"
@@ -119,6 +138,7 @@
119
138
  "allowSyntheticDefaultImports": true,
120
139
  "strictPropertyInitialization": false,
121
140
  "noImplicitAny": false,
141
+ "strictNullChecks": true,
122
142
  "module": "commonjs",
123
143
  "target": "ES2017"
124
144
  }
package/tsconfig.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "compilerOptions": {
3
+ "strictNullChecks": true,
3
4
  "paths": {
4
5
  "mongoose" : ["./types/index.d.ts"]
5
6
  }
6
- },
7
- "strictNullChecks": true
7
+ }
8
8
  }
@@ -1,6 +1,5 @@
1
- import mongodb = require('mongodb');
2
-
3
1
  declare module 'mongoose' {
2
+ import mongodb = require('mongodb');
4
3
 
5
4
  interface AggregateOptions {
6
5
  /**
@@ -1,7 +1,6 @@
1
- import mongodb = require('mongodb');
2
- import events = require('events');
3
-
4
1
  declare module 'mongoose' {
2
+ import mongodb = require('mongodb');
3
+ import events = require('events');
5
4
 
6
5
  /**
7
6
  * Connection ready state
@@ -197,7 +196,7 @@ declare module 'mongoose' {
197
196
  * async function executes successfully and attempt to retry if
198
197
  * there was a retryable error.
199
198
  */
200
- transaction<U = any>(fn: (session: mongodb.ClientSession) => Promise<U>): Promise<U>;
199
+ transaction(fn: (session: mongodb.ClientSession) => Promise<any>): Promise<void>;
201
200
 
202
201
  /** Switches to a different database using the same connection pool. */
203
202
  useDb(name: string, options?: { useCache?: boolean, noListener?: boolean }): Connection;
@@ -206,7 +205,7 @@ declare module 'mongoose' {
206
205
  readonly user: string;
207
206
 
208
207
  /** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model.watch). */
209
- watch<ResultType = any>(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
208
+ watch<ResultType extends mongodb.Document = any>(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
210
209
  }
211
210
 
212
211
  }
package/types/cursor.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import stream = require('stream');
2
-
3
1
  declare module 'mongoose' {
2
+
3
+ import stream = require('stream');
4
+
4
5
  type CursorFlag = 'tailable' | 'oplogReplay' | 'noCursorTimeout' | 'awaitData' | 'partial';
5
6
 
6
7
  interface EachAsyncOptions {
@@ -1,10 +1,15 @@
1
- import mongodb = require('mongodb');
2
-
3
1
  declare module 'mongoose' {
2
+ import mongodb = require('mongodb');
4
3
 
5
4
  /** A list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. */
6
5
  type pathsToSkip = string[] | string;
7
6
 
7
+ /**
8
+ * Generic types for Document:
9
+ * * T - the type of _id
10
+ * * TQueryHelpers - Object with any helpers that should be mixed into the Query type
11
+ * * DocType - the type of the actual Document created
12
+ */
8
13
  class Document<T = any, TQueryHelpers = any, DocType = any> {
9
14
  constructor(doc?: any);
10
15
 
@@ -49,6 +54,9 @@ declare module 'mongoose' {
49
54
  /** Marks a path as valid, removing existing validation errors. */
50
55
  $markValid(path: string): void;
51
56
 
57
+ /** Returns the model with the given name on this document's associated connection. */
58
+ $model<ModelType = Model<unknown>>(name: string): ModelType;
59
+
52
60
  /**
53
61
  * A string containing the current operation that Mongoose is executing
54
62
  * on this document. Can be `null`, `'save'`, `'validate'`, or `'remove'`.
@@ -169,9 +177,6 @@ declare module 'mongoose' {
169
177
  /** The name of the model */
170
178
  modelName: string;
171
179
 
172
- /** Returns the model with the given name on this document's associated connection. */
173
- model<ModelType = Model<unknown>>(name: string): ModelType;
174
-
175
180
  /**
176
181
  * Overwrite all values in this document with the values of `obj`, except
177
182
  * for immutable properties. Behaves similarly to `set()`, except for it
@@ -186,10 +191,10 @@ declare module 'mongoose' {
186
191
  $parent(): Document | undefined;
187
192
 
188
193
  /** Populates document references. */
189
- populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[], callback: Callback<this & Paths>): void;
190
- populate<Paths = {}>(path: string, names: string, callback: Callback<this & Paths>): void;
191
- populate<Paths = {}>(path: string, names: string): Promise<this & Paths>;
192
194
  populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<this & Paths>;
195
+ populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[], callback: Callback<this & Paths>): void;
196
+ populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<unknown>, match?: AnyObject, options?: PopulateOptions): Promise<this & Paths>;
197
+ populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<unknown>, match?: AnyObject, options?: PopulateOptions, callback?: Callback<this & Paths>): void;
193
198
 
194
199
  /** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */
195
200
  populated(path: string): any;
@@ -216,13 +221,11 @@ declare module 'mongoose' {
216
221
  set(value: any): this;
217
222
 
218
223
  /** The return value of this method is used in calls to JSON.stringify(doc). */
219
- toJSON(options: ToObjectOptions & { flattenMaps: false }): LeanDocument<this>;
220
- toJSON(options?: ToObjectOptions): FlattenMaps<LeanDocument<this>>;
221
- toJSON<T = FlattenMaps<DocType>>(options?: ToObjectOptions): T;
224
+ toJSON<T = LeanDocument<DocType>>(options?: ToObjectOptions & { flattenMaps?: true }): FlattenMaps<T>;
225
+ toJSON<T = LeanDocument<DocType>>(options: ToObjectOptions & { flattenMaps: false }): T;
222
226
 
223
227
  /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
224
- toObject(options?: ToObjectOptions): LeanDocument<this>;
225
- toObject<T = DocType>(options?: ToObjectOptions): T;
228
+ toObject<T = LeanDocument<DocType>>(options?: ToObjectOptions): Require_id<T>;
226
229
 
227
230
  /** Clears the modified state on the specified path. */
228
231
  unmarkModified(path: string): void;
@@ -242,6 +245,6 @@ declare module 'mongoose' {
242
245
 
243
246
  /** Executes registered validation rules (skipping asynchronous validators) for this document. */
244
247
  validateSync(options: { pathsToSkip?: pathsToSkip, [k: string]: any }): Error.ValidationError | null;
245
- validateSync(pathsToValidate?: Array<string>, options?: AnyObject): Error.ValidationError | null;
248
+ validateSync(pathsToValidate?: pathsToValidate, options?: AnyObject): Error.ValidationError | null;
246
249
  }
247
- }
250
+ }