mongoose 6.4.1 → 6.4.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.
Files changed (141) hide show
  1. package/.eslintrc.json +4 -2
  2. package/lib/aggregate.js +3 -2
  3. package/lib/cast/date.js +1 -1
  4. package/lib/cast/decimal128.js +1 -1
  5. package/lib/cast/objectid.js +1 -1
  6. package/lib/cast.js +1 -1
  7. package/lib/connection.js +9 -9
  8. package/lib/cursor/AggregationCursor.js +3 -2
  9. package/lib/cursor/QueryCursor.js +5 -4
  10. package/lib/document.js +48 -16
  11. package/lib/drivers/node-mongodb-native/index.js +1 -1
  12. package/lib/error/index.js +12 -12
  13. package/lib/error/messages.js +2 -2
  14. package/lib/error/parallelValidate.js +1 -1
  15. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +1 -1
  16. package/lib/helpers/aggregate/stringifyFunctionOperators.js +1 -1
  17. package/lib/helpers/arrayDepth.js +1 -1
  18. package/lib/helpers/cursor/eachAsync.js +1 -1
  19. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
  20. package/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js +1 -1
  21. package/lib/helpers/discriminator/getConstructor.js +1 -1
  22. package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
  23. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
  24. package/lib/helpers/document/handleSpreadDoc.js +1 -1
  25. package/lib/helpers/each.js +1 -1
  26. package/lib/helpers/get.js +1 -1
  27. package/lib/helpers/getConstructorName.js +1 -1
  28. package/lib/helpers/getDefaultBulkwriteResult.js +1 -1
  29. package/lib/helpers/indexes/applySchemaCollation.js +1 -1
  30. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
  31. package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
  32. package/lib/helpers/indexes/isTextIndex.js +1 -1
  33. package/lib/helpers/isMongooseObject.js +1 -1
  34. package/lib/helpers/isObject.js +1 -1
  35. package/lib/helpers/isPromise.js +1 -1
  36. package/lib/helpers/model/applyHooks.js +1 -1
  37. package/lib/helpers/model/applyStaticHooks.js +1 -1
  38. package/lib/helpers/once.js +1 -1
  39. package/lib/helpers/path/flattenObjectWithDottedPaths.js +1 -1
  40. package/lib/helpers/path/parentPaths.js +1 -1
  41. package/lib/helpers/path/setDottedPath.js +1 -1
  42. package/lib/helpers/pluralize.js +1 -1
  43. package/lib/helpers/populate/SkipPopulateValue.js +1 -1
  44. package/lib/helpers/populate/assignRawDocsToIdStructure.js +1 -1
  45. package/lib/helpers/populate/assignVals.js +1 -1
  46. package/lib/helpers/populate/createPopulateQueryFilter.js +1 -1
  47. package/lib/helpers/populate/getModelsMapForPopulate.js +1 -1
  48. package/lib/helpers/populate/leanPopulateMap.js +1 -1
  49. package/lib/helpers/populate/lookupLocalFields.js +1 -1
  50. package/lib/helpers/populate/markArraySubdocsPopulated.js +1 -1
  51. package/lib/helpers/populate/modelNamesFromRefPath.js +1 -1
  52. package/lib/helpers/populate/removeDeselectedForeignField.js +1 -1
  53. package/lib/helpers/populate/validateRef.js +1 -1
  54. package/lib/helpers/printJestWarning.js +1 -1
  55. package/lib/helpers/processConnectionOptions.js +1 -1
  56. package/lib/helpers/projection/applyProjection.js +1 -1
  57. package/lib/helpers/projection/hasIncludedChildren.js +1 -1
  58. package/lib/helpers/projection/parseProjection.js +1 -1
  59. package/lib/helpers/query/applyGlobalOption.js +1 -1
  60. package/lib/helpers/query/applyQueryMiddleware.js +1 -1
  61. package/lib/helpers/query/cast$expr.js +1 -1
  62. package/lib/helpers/query/castFilterPath.js +1 -1
  63. package/lib/helpers/query/castUpdate.js +4 -4
  64. package/lib/helpers/query/sanitizeFilter.js +1 -1
  65. package/lib/helpers/query/sanitizeProjection.js +1 -1
  66. package/lib/helpers/query/trusted.js +1 -1
  67. package/lib/helpers/query/validOps.js +1 -1
  68. package/lib/helpers/query/wrapThunk.js +1 -1
  69. package/lib/helpers/schema/addAutoId.js +1 -1
  70. package/lib/helpers/schema/applyPlugins.js +1 -1
  71. package/lib/helpers/schema/cleanPositionalOperators.js +1 -1
  72. package/lib/helpers/schema/getKeysInSchemaOrder.js +1 -1
  73. package/lib/helpers/schema/getPath.js +1 -1
  74. package/lib/helpers/schema/handleIdOption.js +1 -1
  75. package/lib/helpers/schema/handleTimestampOption.js +1 -1
  76. package/lib/helpers/specialProperties.js +1 -1
  77. package/lib/helpers/symbols.js +1 -1
  78. package/lib/helpers/timers.js +1 -1
  79. package/lib/helpers/timestamps/setupTimestamps.js +1 -1
  80. package/lib/helpers/topology/allServersUnknown.js +1 -1
  81. package/lib/helpers/topology/isAtlas.js +1 -1
  82. package/lib/helpers/topology/isSSLError.js +1 -1
  83. package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
  84. package/lib/helpers/update/castArrayFilters.js +1 -1
  85. package/lib/helpers/update/moveImmutableProperties.js +1 -1
  86. package/lib/helpers/update/removeUnusedArrayFilters.js +1 -1
  87. package/lib/helpers/update/updatedPathsByArrayFilter.js +1 -1
  88. package/lib/index.js +7 -4
  89. package/lib/model.js +22 -21
  90. package/lib/options/PopulateOptions.js +1 -1
  91. package/lib/options/SchemaArrayOptions.js +3 -3
  92. package/lib/options/SchemaBufferOptions.js +2 -2
  93. package/lib/options/SchemaDateOptions.js +3 -3
  94. package/lib/options/SchemaDocumentArrayOptions.js +3 -3
  95. package/lib/options/SchemaMapOptions.js +2 -2
  96. package/lib/options/SchemaNumberOptions.js +5 -5
  97. package/lib/options/SchemaObjectIdOptions.js +3 -3
  98. package/lib/options/SchemaStringOptions.js +8 -8
  99. package/lib/options/SchemaSubdocumentOptions.js +2 -2
  100. package/lib/options/SchemaTypeOptions.js +15 -15
  101. package/lib/options/VirtualOptions.js +12 -12
  102. package/lib/options/propertyOptions.js +1 -1
  103. package/lib/options/removeOptions.js +1 -1
  104. package/lib/options/saveOptions.js +1 -1
  105. package/lib/plugins/trackTransaction.js +1 -1
  106. package/lib/query.js +74 -71
  107. package/lib/schema/SubdocumentPath.js +10 -6
  108. package/lib/schema/array.js +3 -3
  109. package/lib/schema/boolean.js +5 -5
  110. package/lib/schema/buffer.js +2 -2
  111. package/lib/schema/date.js +2 -2
  112. package/lib/schema/decimal128.js +2 -2
  113. package/lib/schema/documentarray.js +12 -8
  114. package/lib/schema/mixed.js +2 -2
  115. package/lib/schema/number.js +2 -2
  116. package/lib/schema/objectid.js +2 -2
  117. package/lib/schema/string.js +2 -2
  118. package/lib/schema/symbols.js +1 -1
  119. package/lib/schema.js +72 -37
  120. package/lib/schematype.js +9 -10
  121. package/lib/types/DocumentArray/methods/index.js +2 -2
  122. package/lib/types/buffer.js +30 -28
  123. package/lib/types/decimal128.js +4 -4
  124. package/lib/types/map.js +70 -0
  125. package/lib/types/objectid.js +1 -1
  126. package/lib/types/subdocument.js +1 -1
  127. package/lib/virtualtype.js +5 -5
  128. package/package.json +13 -13
  129. package/types/collection.d.ts +1 -1
  130. package/types/document.d.ts +4 -4
  131. package/types/expressions.d.ts +27 -8
  132. package/types/index.d.ts +2 -1
  133. package/types/indexes.d.ts +2 -2
  134. package/types/inferschematype.d.ts +51 -33
  135. package/types/middlewares.d.ts +1 -1
  136. package/types/models.d.ts +8 -7
  137. package/types/mongooseoptions.d.ts +1 -1
  138. package/types/pipelinestage.d.ts +1 -1
  139. package/types/query.d.ts +6 -1
  140. package/types/schemaoptions.d.ts +1 -1
  141. package/types/utility.d.ts +7 -0
package/lib/types/map.js CHANGED
@@ -42,6 +42,14 @@ class MongooseMap extends Map {
42
42
  super.set(key, value);
43
43
  }
44
44
 
45
+ /**
46
+ * Overwrites native Map's `get()` function to support Mongoose getters.
47
+ *
48
+ * @api public
49
+ * @method get
50
+ * @memberOf Map
51
+ */
52
+
45
53
  get(key, options) {
46
54
  if (isBsonType(key, 'ObjectID')) {
47
55
  key = key.toString();
@@ -54,6 +62,20 @@ class MongooseMap extends Map {
54
62
  return this.$__schemaType.applyGetters(super.get(key), this.$__parent);
55
63
  }
56
64
 
65
+ /**
66
+ * Overwrites native Map's `set()` function to support setters, `populate()`,
67
+ * and change tracking. Note that Mongoose maps _only_ support strings and
68
+ * ObjectIds as keys.
69
+ *
70
+ * #### Example:
71
+ * doc.myMap.set('test', 42); // works
72
+ * doc.myMap.set({ obj: 42 }, 42); // Throws "Mongoose maps only support string keys"
73
+ *
74
+ * @api public
75
+ * @method set
76
+ * @memberOf Map
77
+ */
78
+
57
79
  set(key, value) {
58
80
  if (isBsonType(key, 'ObjectID')) {
59
81
  key = key.toString();
@@ -108,6 +130,14 @@ class MongooseMap extends Map {
108
130
  }
109
131
  }
110
132
 
133
+ /**
134
+ * Overwrites native Map's `clear()` function to support change tracking.
135
+ *
136
+ * @api public
137
+ * @method clear
138
+ * @memberOf Map
139
+ */
140
+
111
141
  clear() {
112
142
  super.clear();
113
143
  const parent = this.$__parent;
@@ -116,6 +146,14 @@ class MongooseMap extends Map {
116
146
  }
117
147
  }
118
148
 
149
+ /**
150
+ * Overwrites native Map's `delete()` function to support change tracking.
151
+ *
152
+ * @api public
153
+ * @method delete
154
+ * @memberOf Map
155
+ */
156
+
119
157
  delete(key) {
120
158
  if (isBsonType(key, 'ObjectID')) {
121
159
  key = key.toString();
@@ -125,6 +163,14 @@ class MongooseMap extends Map {
125
163
  super.delete(key);
126
164
  }
127
165
 
166
+ /**
167
+ * Converts this map to a native JavaScript Map so the MongoDB driver can serialize it.
168
+ *
169
+ * @api public
170
+ * @method toBSON
171
+ * @memberOf Map
172
+ */
173
+
128
174
  toBSON() {
129
175
  return new Map(this);
130
176
  }
@@ -146,6 +192,21 @@ class MongooseMap extends Map {
146
192
  return this.constructor.prototype.toObject.apply(this, arguments);
147
193
  }
148
194
 
195
+ /**
196
+ * Converts this map to a native JavaScript Map for `JSON.stringify()`. Set
197
+ * the `flattenMaps` option to convert this map to a POJO instead.
198
+ *
199
+ * #### Example:
200
+ * doc.myMap.toJSON() instanceof Map; // true
201
+ * doc.myMap.toJSON({ flattenMaps: true }) instanceof Map; // false
202
+ *
203
+ * @api public
204
+ * @method toJSON
205
+ * @param {Object} [options]
206
+ * @param {Boolean} [options.flattenMaps=false] set to `true` to convert the map to a POJO rather than a native JavaScript map
207
+ * @memberOf Map
208
+ */
209
+
149
210
  toJSON(options) {
150
211
  if (typeof (options && options.flattenMaps) === 'boolean' ? options.flattenMaps : true) {
151
212
  const ret = {};
@@ -209,6 +270,15 @@ Object.defineProperty(MongooseMap.prototype, '$__schemaType', {
209
270
  configurable: false
210
271
  });
211
272
 
273
+ /**
274
+ * Set to `true` for all Mongoose map instances
275
+ *
276
+ * @api public
277
+ * @property $isMongooseMap
278
+ * @memberOf MongooseMap
279
+ * @instance
280
+ */
281
+
212
282
  Object.defineProperty(MongooseMap.prototype, '$isMongooseMap', {
213
283
  enumerable: false,
214
284
  writable: false,
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * ObjectId type constructor
3
3
  *
4
- * #### Example
4
+ * #### Example:
5
5
  *
6
6
  * const id = new mongoose.Types.ObjectId;
7
7
  *
@@ -188,7 +188,7 @@ Subdocument.prototype.isModified = function(paths, modifiedPaths) {
188
188
  * @param {String} path the field to mark as valid
189
189
  * @api private
190
190
  * @method $markValid
191
- * @receiver Subdocument
191
+ * @memberOf Subdocument
192
192
  */
193
193
 
194
194
  Subdocument.prototype.$markValid = function(path) {
@@ -75,7 +75,7 @@ VirtualType.prototype.clone = function() {
75
75
  * Mongoose calls the getter function with the below 3 parameters.
76
76
  *
77
77
  * - `value`: the value returned by the previous getter. If there is only one getter, `value` will be `undefined`.
78
- * - `virtual`: the virtual object you called `.get()` on
78
+ * - `virtual`: the virtual object you called `.get()` on.
79
79
  * - `doc`: the document this virtual is attached to. Equivalent to `this`.
80
80
  *
81
81
  * #### Example:
@@ -85,7 +85,7 @@ VirtualType.prototype.clone = function() {
85
85
  * return this.name.first + ' ' + this.name.last;
86
86
  * });
87
87
  *
88
- * @param {Function(Any, VirtualType, Document)} fn
88
+ * @param {function} fn
89
89
  * @return {VirtualType} this
90
90
  * @api public
91
91
  */
@@ -100,8 +100,8 @@ VirtualType.prototype.get = function(fn) {
100
100
  *
101
101
  * Mongoose calls the setter function with the below 3 parameters.
102
102
  *
103
- * - `value`: the value being set
104
- * - `virtual`: the virtual object you're calling `.set()` on
103
+ * - `value`: the value being set.
104
+ * - `virtual`: the virtual object you're calling `.set()` on.
105
105
  * - `doc`: the document this virtual is attached to. Equivalent to `this`.
106
106
  *
107
107
  * #### Example:
@@ -120,7 +120,7 @@ VirtualType.prototype.get = function(fn) {
120
120
  * doc.name.first; // 'Jean-Luc'
121
121
  * doc.name.last; // 'Picard'
122
122
  *
123
- * @param {Function(Any, VirtualType, Document)} fn
123
+ * @param {function} fn
124
124
  * @return {VirtualType} this
125
125
  * @api public
126
126
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "6.4.1",
4
+ "version": "6.4.4",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -28,9 +28,9 @@
28
28
  "sift": "16.0.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@babel/core": "7.18.2",
32
- "@typescript-eslint/eslint-plugin": "5.27.0",
33
- "@typescript-eslint/parser": "5.27.0",
31
+ "@babel/core": "7.18.6",
32
+ "@typescript-eslint/eslint-plugin": "5.30.3",
33
+ "@typescript-eslint/parser": "5.30.3",
34
34
  "acquit": "1.2.1",
35
35
  "acquit-ignore": "0.2.0",
36
36
  "acquit-require": "0.1.1",
@@ -40,19 +40,19 @@
40
40
  "benchmark": "2.1.4",
41
41
  "bluebird": "3.7.2",
42
42
  "buffer": "^5.6.0",
43
- "cheerio": "1.0.0-rc.11",
43
+ "cheerio": "1.0.0-rc.12",
44
44
  "crypto-browserify": "3.12.0",
45
- "dox": "0.3.1",
46
- "eslint": "8.16.0",
45
+ "dox": "0.9.1",
46
+ "eslint": "8.19.0",
47
47
  "eslint-plugin-mocha-no-only": "1.1.1",
48
48
  "highlight.js": "11.5.1",
49
49
  "lodash.isequal": "4.5.0",
50
50
  "lodash.isequalwith": "4.4.0",
51
- "marked": "4.0.16",
51
+ "marked": "4.0.17",
52
52
  "mkdirp": "^1.0.4",
53
53
  "mocha": "10.0.0",
54
54
  "moment": "2.x",
55
- "mongodb-memory-server": "8.6.0",
55
+ "mongodb-memory-server": "8.7.2",
56
56
  "ncp": "^2.0.0",
57
57
  "nyc": "15.1.0",
58
58
  "pug": "3.0.2",
@@ -62,9 +62,9 @@
62
62
  "stream-browserify": "3.0.0",
63
63
  "ts-benchmark": "^1.0.2",
64
64
  "tsd": "0.20.0",
65
- "typescript": "4.7.2",
65
+ "typescript": "4.7.4",
66
66
  "uuid": "8.3.2",
67
- "webpack": "5.72.1"
67
+ "webpack": "5.73.0"
68
68
  },
69
69
  "directories": {
70
70
  "lib": "./lib/mongoose"
@@ -98,7 +98,7 @@
98
98
  "test-tsd": "node ./test/types/check-types-filename && tsd",
99
99
  "tdd": "mocha ./test/*.test.js --inspect --watch --recursive --watch-files ./**/*.{js,ts}",
100
100
  "test-coverage": "nyc --reporter=html --reporter=text npm test",
101
- "ts-benchmark": "ts-benchmark -p ./benchmarks/typescript/simple -f 17 18 29 32",
101
+ "ts-benchmark": "node ./benchmarks/typescript.js",
102
102
  "ts-benchmark-watch": "ts-benchmark -p ./benchmarks/typescript/simple -w ./types -i -s -f 17 18 29 32 -b master"
103
103
  },
104
104
  "main": "./index.js",
@@ -145,4 +145,4 @@
145
145
  "target": "ES2017"
146
146
  }
147
147
  }
148
- }
148
+ }
@@ -43,4 +43,4 @@ declare module 'mongoose' {
43
43
  getIndexes(): ReturnType<mongodb.Collection<T>['indexInformation']>;
44
44
  }
45
45
  let Collection: Collection;
46
- }
46
+ }
@@ -200,10 +200,10 @@ declare module 'mongoose' {
200
200
  $parent(): Document | undefined;
201
201
 
202
202
  /** Populates document references. */
203
- populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<this & Paths>;
204
- populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[], callback: Callback<this & Paths>): void;
205
- populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions): Promise<this & Paths>;
206
- populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions, callback?: Callback<this & Paths>): void;
203
+ populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<MergeType<this, Paths>>;
204
+ populate<Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[], callback: Callback<MergeType<this, Paths>>): void;
205
+ populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions): Promise<MergeType<this, Paths>>;
206
+ populate<Paths = {}>(path: string, select?: string | AnyObject, model?: Model<any>, match?: AnyObject, options?: PopulateOptions, callback?: Callback<MergeType<this, Paths>>): void;
207
207
 
208
208
  /** Gets _id(s) used during population of the given `path`. If the path was not populated, returns `undefined`. */
209
209
  populated(path: string): any;
@@ -32,7 +32,7 @@ declare module 'mongoose' {
32
32
  *
33
33
  * @see https://docs.mongodb.com/manual/reference/operator/aggregation/add/#mongodb-expression-exp.-add
34
34
  */
35
- $add: (NumberExpression | DateExpression)[];
35
+ $add: Expression[];
36
36
  }
37
37
 
38
38
  export interface Ceil {
@@ -1034,7 +1034,7 @@ declare module 'mongoose' {
1034
1034
  *
1035
1035
  * @see https://docs.mongodb.com/manual/reference/operator/aggregation/ne/#mongodb-expression-exp.-ne
1036
1036
  */
1037
- $ne: Expression | [Expression, Expression] | null;
1037
+ $ne: Expression | [Expression, Expression | NullExpression] | null;
1038
1038
  }
1039
1039
 
1040
1040
  export interface Cond {
@@ -1043,7 +1043,7 @@ declare module 'mongoose' {
1043
1043
  *
1044
1044
  * @see https://docs.mongodb.com/manual/reference/operator/aggregation/cond/#mongodb-expression-exp.-cond
1045
1045
  */
1046
- $cond: { if: BooleanExpression, then: AnyExpression, else: AnyExpression } | [BooleanExpression, AnyExpression, AnyExpression];
1046
+ $cond: { if: Expression, then: AnyExpression, else: AnyExpression } | [BooleanExpression, AnyExpression, AnyExpression];
1047
1047
  }
1048
1048
 
1049
1049
  export interface IfNull {
@@ -1957,7 +1957,7 @@ declare module 'mongoose' {
1957
1957
  * @version 5.0
1958
1958
  * @see https://docs.mongodb.com/manual/reference/operator/aggregation/addToSet/#mongodb-expression-exp.-addToSet
1959
1959
  */
1960
- $addToSet: ArrayExpression;
1960
+ $addToSet: Expression | Record<string, Expression>;
1961
1961
  }
1962
1962
 
1963
1963
  export interface Avg {
@@ -1967,7 +1967,7 @@ declare module 'mongoose' {
1967
1967
  * @version 5.0
1968
1968
  * @see https://docs.mongodb.com/manual/reference/operator/aggregation/avg/#mongodb-expression-exp.-avg
1969
1969
  */
1970
- $avg: ArrayExpression;
1970
+ $avg: Expression;
1971
1971
  }
1972
1972
 
1973
1973
  export interface Count {
@@ -2316,6 +2316,21 @@ declare module 'mongoose' {
2316
2316
  $toObjectId: Expression;
2317
2317
  }
2318
2318
 
2319
+ export interface Top {
2320
+ $top: {
2321
+ sortBy: AnyObject,
2322
+ output: Expression
2323
+ };
2324
+ }
2325
+
2326
+ export interface TopN {
2327
+ $topN: {
2328
+ n: Expression,
2329
+ sortBy: AnyObject,
2330
+ output: Expression
2331
+ };
2332
+ }
2333
+
2319
2334
  export interface ToString {
2320
2335
  /**
2321
2336
  * Converts a value to a string. If the value cannot be converted to a string, $toString errors. If the value is
@@ -2406,7 +2421,10 @@ declare module 'mongoose' {
2406
2421
  TypeExpressionOperator |
2407
2422
  AccumulatorOperator |
2408
2423
  VariableExpressionOperator |
2409
- WindowOperator;
2424
+ WindowOperator |
2425
+ Expression.Top |
2426
+ Expression.TopN |
2427
+ any;
2410
2428
 
2411
2429
  export type NullExpression = null;
2412
2430
 
@@ -2478,7 +2496,8 @@ declare module 'mongoose' {
2478
2496
  DataSizeOperatorReturningNumber |
2479
2497
  CustomAggregationExpressionOperatorReturningAny |
2480
2498
  TypeExpressionOperatorReturningNumber |
2481
- DateExpression;
2499
+ DateExpression |
2500
+ DateExpressionOperatorReturningNumber;
2482
2501
 
2483
2502
  export type ObjectExpression =
2484
2503
  Path |
@@ -2879,4 +2898,4 @@ declare module 'mongoose' {
2879
2898
  export type DateExpressionOperatorReturningString =
2880
2899
  Expression.DateToString;
2881
2900
 
2882
- }
2901
+ }
package/types/index.d.ts CHANGED
@@ -166,7 +166,7 @@ declare module 'mongoose' {
166
166
  /**
167
167
  * Create a new schema
168
168
  */
169
- constructor(definition?: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>> | DocType, options?: SchemaOptions<TPathTypeKey, DocType, TInstanceMethods, TQueryHelpers, TStaticMethods>);
169
+ constructor(definition?: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>> | DocType, options?: SchemaOptions<TPathTypeKey, FlatRecord<DocType>, TInstanceMethods, TQueryHelpers, TStaticMethods>);
170
170
 
171
171
  /** Adds key path / schema type pairs to this schema. */
172
172
  add(obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>> | Schema, prefix?: string): this;
@@ -227,6 +227,7 @@ declare module 'mongoose' {
227
227
  obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>>;
228
228
 
229
229
  /** Gets/sets schema paths. */
230
+ path<pathGeneric extends keyof EnforcedDocType>(path: pathGeneric): SchemaType<EnforcedDocType[pathGeneric]>;
230
231
  path<ResultType extends SchemaType = SchemaType>(path: string): ResultType;
231
232
  path(path: string, constructor: any): this;
232
233
 
@@ -93,6 +93,6 @@ declare module 'mongoose' {
93
93
  * ```
94
94
  */
95
95
  expires?: number | string;
96
- weights?: AnyObject;
96
+ weights?: Record<string, number>;
97
97
  }
98
- }
98
+ }
@@ -1,4 +1,4 @@
1
- import { Schema, InferSchemaType, SchemaType, SchemaTypeOptions, TypeKeyBaseType } from 'mongoose';
1
+ import { Schema, InferSchemaType, SchemaType, SchemaTypeOptions, TypeKeyBaseType, Types, NumberSchemaDefinition, StringSchemaDefinition, BooleanSchemaDefinition, DateSchemaDefinition } from 'mongoose';
2
2
 
3
3
  declare module 'mongoose' {
4
4
  /**
@@ -6,13 +6,13 @@ declare module 'mongoose' {
6
6
  * @description Obtains document schema type from document Definition OR returns enforced schema type if it's provided.
7
7
  * @param {DocDefinition} DocDefinition A generic equals to the type of document definition "provided in as first parameter in Schema constructor".
8
8
  * @param {EnforcedDocType} EnforcedDocType A generic type enforced by user "provided before schema constructor".
9
- * @param {TypeKey} TypeKey A generic of literal string type.
9
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
10
10
  */
11
- type ObtainDocumentType<DocDefinition, EnforcedDocType = any, TypeKey extends TypeKeyBaseType = DefaultTypeKey> =
12
- IsItRecordAndNotAny<EnforcedDocType> extends true ? EnforcedDocType : {
13
- [K in keyof (RequiredPaths<DocDefinition> &
14
- OptionalPaths<DocDefinition>)]: ObtainDocumentPathType<DocDefinition[K], TypeKey>;
15
- };
11
+ type ObtainDocumentType<DocDefinition, EnforcedDocType = any, TypeKey extends TypeKeyBaseType = DefaultTypeKey> =
12
+ IsItRecordAndNotAny<EnforcedDocType> extends true ? EnforcedDocType : {
13
+ [K in keyof (RequiredPaths<DocDefinition, TypeKey> &
14
+ OptionalPaths<DocDefinition, TypeKey>)]: ObtainDocumentPathType<DocDefinition[K], TypeKey>;
15
+ };
16
16
 
17
17
  /**
18
18
  * @summary Obtains document schema type from Schema instance.
@@ -64,10 +64,22 @@ type IfEquals<T, U, Y = true, N = false> =
64
64
  (<G>() => G extends U ? 1 : 0) ? Y : N;
65
65
 
66
66
  /**
67
- * @summary Required path base type.
68
- * @description It helps to check whereas if a path is required OR optional.
67
+ * @summary Checks if a document path is required or optional.
68
+ * @param {P} P Document path.
69
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
69
70
  */
70
- type RequiredPathBaseType = { required: true | [true, string | undefined] };
71
+ type IsPathRequired<P, TypeKey extends TypeKeyBaseType> =
72
+ P extends { required: true | [true, string | undefined] } | ArrayConstructor | any[]
73
+ ? true
74
+ : P extends (Record<TypeKey, ArrayConstructor | any[]>)
75
+ ? P extends { default: undefined }
76
+ ? false
77
+ : true
78
+ : P extends (Record<TypeKey, NumberSchemaDefinition | StringSchemaDefinition | BooleanSchemaDefinition | DateSchemaDefinition>)
79
+ ? P extends { default: ResolvePathType<P[TypeKey]> }
80
+ ? true
81
+ : false
82
+ : false;
71
83
 
72
84
  /**
73
85
  * @summary Path base type defined by using TypeKey
@@ -79,37 +91,41 @@ type PathWithTypePropertyBaseType<TypeKey extends TypeKeyBaseType> = { [k in Typ
79
91
  /**
80
92
  * @summary A Utility to obtain schema's required path keys.
81
93
  * @param {T} T A generic refers to document definition.
94
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
82
95
  * @returns required paths keys of document definition.
83
96
  */
84
- type RequiredPathKeys<T> = {
85
- [K in keyof T]: T[K] extends RequiredPathBaseType ? IfEquals<T[K], any, never, K> : never;
97
+ type RequiredPathKeys<T, TypeKey extends TypeKeyBaseType> = {
98
+ [K in keyof T]: IsPathRequired<T[K], TypeKey> extends true ? IfEquals<T[K], any, never, K> : never;
86
99
  }[keyof T];
87
100
 
88
101
  /**
89
102
  * @summary A Utility to obtain schema's required paths.
90
103
  * @param {T} T A generic refers to document definition.
104
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
91
105
  * @returns a record contains required paths with the corresponding type.
92
106
  */
93
- type RequiredPaths<T> = {
94
- [K in RequiredPathKeys<T>]: T[K];
107
+ type RequiredPaths<T, TypeKey extends TypeKeyBaseType> = {
108
+ [K in RequiredPathKeys<T, TypeKey>]: T[K];
95
109
  };
96
110
 
97
111
  /**
98
112
  * @summary A Utility to obtain schema's optional path keys.
99
113
  * @param {T} T A generic refers to document definition.
114
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
100
115
  * @returns optional paths keys of document definition.
101
116
  */
102
- type OptionalPathKeys<T> = {
103
- [K in keyof T]: T[K] extends RequiredPathBaseType ? never : K;
117
+ type OptionalPathKeys<T, TypeKey extends TypeKeyBaseType> = {
118
+ [K in keyof T]: IsPathRequired<T[K], TypeKey> extends true ? never : K;
104
119
  }[keyof T];
105
120
 
106
121
  /**
107
122
  * @summary A Utility to obtain schema's optional paths.
108
123
  * @param {T} T A generic refers to document definition.
124
+ * @param {TypeKey} TypeKey A generic of literal string type."Refers to the property used for path type definition".
109
125
  * @returns a record contains optional paths with the corresponding type.
110
126
  */
111
- type OptionalPaths<T> = {
112
- [K in OptionalPathKeys<T>]?: T[K];
127
+ type OptionalPaths<T, TypeKey extends TypeKeyBaseType> = {
128
+ [K in OptionalPathKeys<T, TypeKey>]?: T[K];
113
129
  };
114
130
 
115
131
  /**
@@ -138,18 +154,20 @@ type PathEnumOrString<T extends SchemaTypeOptions<string>['enum']> = T extends (
138
154
  * @returns Number, "Number" or "number" will be resolved to string type.
139
155
  */
140
156
  type ResolvePathType<PathValueType, Options extends SchemaTypeOptions<PathValueType> = {}> =
141
- PathValueType extends (infer Item)[] ? IfEquals<Item, never, any, ResolvePathType<Item>>[] :
142
- PathValueType extends StringConstructor | 'string' | 'String' | typeof Schema.Types.String ? PathEnumOrString<Options['enum']> :
143
- PathValueType extends NumberConstructor | 'number' | 'Number' | typeof Schema.Types.Number ? number :
144
- PathValueType extends DateConstructor | 'date' | 'Date' | typeof Schema.Types.Date ? Date :
145
- PathValueType extends typeof Buffer | 'buffer' | 'Buffer' | typeof Schema.Types.Buffer ? Buffer :
146
- PathValueType extends BooleanConstructor | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean ? boolean :
147
- PathValueType extends 'objectId' | 'ObjectId' | typeof Schema.Types.ObjectId ? Schema.Types.ObjectId :
148
- PathValueType extends 'decimal128' | 'Decimal128' | typeof Schema.Types.Decimal128 ? Schema.Types.Decimal128 :
149
- PathValueType extends MapConstructor ? Map<string, ResolvePathType<Options['of']>> :
150
- PathValueType extends ArrayConstructor ? any[] :
151
- PathValueType extends typeof Schema.Types.Mixed ? any:
152
- IfEquals<PathValueType, ObjectConstructor> extends true ? any:
153
- IfEquals<PathValueType, {}> extends true ? any:
154
- PathValueType extends typeof SchemaType ? PathValueType['prototype'] :
155
- unknown;
157
+ PathValueType extends Schema ? InferSchemaType<PathValueType> :
158
+ PathValueType extends (infer Item)[] ? IfEquals<Item, never, any, ResolvePathType<Item>>[] :
159
+ PathValueType extends StringSchemaDefinition ? PathEnumOrString<Options['enum']> :
160
+ PathValueType extends NumberSchemaDefinition ? number :
161
+ PathValueType extends DateSchemaDefinition ? Date :
162
+ PathValueType extends typeof Buffer | 'buffer' | 'Buffer' | typeof Schema.Types.Buffer ? Buffer :
163
+ PathValueType extends BooleanSchemaDefinition ? boolean :
164
+ PathValueType extends 'objectId' | 'ObjectId' | typeof Schema.Types.ObjectId ? Types.ObjectId :
165
+ PathValueType extends 'decimal128' | 'Decimal128' | typeof Schema.Types.Decimal128 ? Types.Decimal128 :
166
+ PathValueType extends MapConstructor ? Map<string, ResolvePathType<Options['of']>> :
167
+ PathValueType extends ArrayConstructor ? any[] :
168
+ PathValueType extends typeof Schema.Types.Mixed ? any:
169
+ IfEquals<PathValueType, ObjectConstructor> extends true ? any:
170
+ IfEquals<PathValueType, {}> extends true ? any:
171
+ PathValueType extends typeof SchemaType ? PathValueType['prototype'] :
172
+ PathValueType extends {} ? PathValueType :
173
+ unknown;
@@ -11,4 +11,4 @@ declare module 'mongoose' {
11
11
  type PreSaveMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError, opts: SaveOptions) => void | Promise<void>;
12
12
  type PostMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
13
13
  type ErrorHandlingMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void;
14
- }
14
+ }
package/types/models.d.ts CHANGED
@@ -106,7 +106,7 @@ declare module 'mongoose' {
106
106
  checkKeys?: boolean;
107
107
  j?: boolean;
108
108
  safe?: boolean | WriteConcern;
109
- timestamps?: boolean;
109
+ timestamps?: boolean | QueryTimestampsConfig;
110
110
  validateBeforeSave?: boolean;
111
111
  validateModifiedOnly?: boolean;
112
112
  w?: number | string;
@@ -163,11 +163,11 @@ declare module 'mongoose' {
163
163
  countDocuments(callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
164
164
 
165
165
  /** Creates a new document or documents */
166
- create<DocContents = T>(docs: Array<T | DocContents>, options?: SaveOptions): Promise<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>[]>;
167
- create<DocContents = T>(docs: Array<T | DocContents>, callback: Callback<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>[]>): void;
168
- create<DocContents = T>(doc: DocContents | T): Promise<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>;
169
- create<DocContents = T>(...docs: Array<T | DocContents>): Promise<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>[]>;
170
- create<DocContents = T>(doc: T | DocContents, callback: Callback<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>): void;
166
+ create<DocContents = AnyKeys<T>>(docs: Array<T | DocContents>, options?: SaveOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
167
+ create<DocContents = AnyKeys<T>>(docs: Array<T | DocContents>, callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>): void;
168
+ create<DocContents = AnyKeys<T>>(doc: DocContents | T): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
169
+ create<DocContents = AnyKeys<T>>(...docs: Array<T | DocContents>): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
170
+ create<DocContents = AnyKeys<T>>(doc: T | DocContents, callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>): void;
171
171
 
172
172
  /**
173
173
  * Create the collection for this model. By default, if no indexes are specified,
@@ -351,6 +351,7 @@ declare module 'mongoose' {
351
351
  findOneAndRemove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
352
352
 
353
353
  /** Creates a `findOneAndReplace` query: atomically finds the given document and replaces it with `replacement`. */
354
+ findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, replacement: T | AnyObject, options: QueryOptions<T> & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
354
355
  findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, replacement: T | AnyObject, options: QueryOptions<T> & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
355
356
  findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
356
357
 
@@ -431,4 +432,4 @@ declare module 'mongoose' {
431
432
  where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(obj: object): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
432
433
  where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
433
434
  }
434
- }
435
+ }
@@ -190,4 +190,4 @@ declare module 'mongoose' {
190
190
  */
191
191
  toObject?: ToObjectOptions;
192
192
  }
193
- }
193
+ }
@@ -212,7 +212,7 @@ declare module 'mongoose' {
212
212
 
213
213
  export interface Set {
214
214
  /** [`$set` reference](https://docs.mongodb.com/manual/reference/operator/aggregation/set/) */
215
- $set: Record<string, AnyExpression>
215
+ $set: Record<string, AnyExpression | any>
216
216
  }
217
217
 
218
218
  export interface SetWindowFields {
package/types/query.d.ts CHANGED
@@ -90,6 +90,11 @@ declare module 'mongoose' {
90
90
  [key: string]: any;
91
91
  };
92
92
 
93
+ interface QueryTimestampsConfig {
94
+ createdAt?: boolean;
95
+ updatedAt?: boolean;
96
+ }
97
+
93
98
  interface QueryOptions<DocType = unknown> extends
94
99
  PopulateOption,
95
100
  SessionOption {
@@ -157,7 +162,7 @@ declare module 'mongoose' {
157
162
  * skip timestamps for this update. Note that this allows you to overwrite
158
163
  * timestamps. Does nothing if schema-level timestamps are not set.
159
164
  */
160
- timestamps?: boolean;
165
+ timestamps?: boolean | QueryTimestampsConfig;
161
166
  upsert?: boolean;
162
167
  writeConcern?: mongodb.WriteConcern;
163
168
 
@@ -203,4 +203,4 @@ declare module 'mongoose' {
203
203
  */
204
204
  query?: Record<any, <T extends QueryWithHelpers<unknown, DocType>>(this: T, ...args: any) => T> | QueryHelpers,
205
205
  }
206
- }
206
+ }
@@ -12,4 +12,11 @@ declare module 'mongoose' {
12
12
 
13
13
  type MergeType<A, B> = Omit<A, keyof B> & B;
14
14
 
15
+ /**
16
+ * @summary Converts Unions to one record "object".
17
+ * @description It makes intellisense dialog box easier to read as a single object instead of showing that in multiple object unions.
18
+ * @param {T} T The type to be converted.
19
+ */
20
+ type FlatRecord<T> = { [K in keyof T]: T[K] };
21
+
15
22
  }