@datanimbus/mongoose 9.13.1 → 9.13.2

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 (302) hide show
  1. package/README.md +80 -70
  2. package/eslint.config.mjs +202 -0
  3. package/index.js +2 -1
  4. package/lib/aggregate.js +276 -174
  5. package/lib/cast/bigint.js +46 -0
  6. package/lib/cast/boolean.js +3 -3
  7. package/lib/cast/decimal128.js +4 -1
  8. package/lib/cast/double.js +56 -0
  9. package/lib/cast/int32.js +42 -0
  10. package/lib/cast/number.js +6 -6
  11. package/lib/cast/objectid.js +3 -3
  12. package/lib/cast/string.js +3 -3
  13. package/lib/cast/uuid.js +35 -0
  14. package/lib/cast.js +100 -92
  15. package/lib/collection.js +31 -22
  16. package/lib/connection.js +792 -507
  17. package/lib/constants.js +73 -0
  18. package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
  19. package/lib/cursor/changeStream.js +218 -0
  20. package/lib/cursor/queryCursor.js +676 -0
  21. package/lib/defaults/schemaDefaultsCache.js +62 -0
  22. package/lib/document.js +2419 -1306
  23. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  24. package/lib/drivers/node-mongodb-native/collection.js +101 -135
  25. package/lib/drivers/node-mongodb-native/connection.js +386 -28
  26. package/lib/drivers/node-mongodb-native/index.js +3 -5
  27. package/lib/error/browserMissingSchema.js +5 -4
  28. package/lib/error/bulkSaveIncompleteError.js +44 -0
  29. package/lib/error/cast.js +30 -21
  30. package/lib/error/createCollectionsError.js +26 -0
  31. package/lib/error/divergentArray.js +11 -9
  32. package/lib/error/eachAsyncMultiError.js +2 -2
  33. package/lib/error/index.js +38 -29
  34. package/lib/error/invalidSchemaOption.js +32 -0
  35. package/lib/error/messages.js +4 -3
  36. package/lib/error/missingSchema.js +8 -6
  37. package/lib/error/notFound.js +7 -5
  38. package/lib/error/objectExpected.js +9 -8
  39. package/lib/error/objectParameter.js +12 -11
  40. package/lib/error/overwriteModel.js +7 -6
  41. package/lib/error/parallelSave.js +11 -8
  42. package/lib/error/parallelValidate.js +9 -7
  43. package/lib/error/serverSelection.js +1 -0
  44. package/lib/error/setOptionError.js +11 -9
  45. package/lib/error/strict.js +12 -10
  46. package/lib/error/strictPopulate.js +11 -9
  47. package/lib/error/syncIndexes.js +2 -2
  48. package/lib/error/validation.js +11 -17
  49. package/lib/error/validator.js +9 -8
  50. package/lib/error/version.js +12 -10
  51. package/lib/filters/operators.js +8 -0
  52. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
  53. package/lib/helpers/buildMiddlewareFilter.js +42 -0
  54. package/lib/helpers/clone.js +121 -35
  55. package/lib/helpers/common.js +7 -7
  56. package/lib/helpers/cursor/eachAsync.js +14 -11
  57. package/lib/helpers/cursor/waitForInitialization.js +17 -0
  58. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  59. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
  60. package/lib/helpers/discriminator/getConstructor.js +9 -6
  61. package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
  62. package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
  63. package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
  64. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
  65. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
  66. package/lib/helpers/document/applyDefaults.js +82 -14
  67. package/lib/helpers/document/applyTimestamps.js +106 -0
  68. package/lib/helpers/document/applyVirtuals.js +147 -0
  69. package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
  70. package/lib/helpers/document/compile.js +20 -15
  71. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  72. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
  73. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  74. package/lib/helpers/document/isInPathsToSave.js +24 -0
  75. package/lib/helpers/document/toObjectRecursive.js +49 -0
  76. package/lib/helpers/get.js +1 -1
  77. package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
  78. package/lib/helpers/getInheritedProperty.js +28 -0
  79. package/lib/helpers/getOwnProperty.js +19 -0
  80. package/lib/helpers/indexes/applySchemaCollation.js +1 -1
  81. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
  82. package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
  83. package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
  84. package/lib/helpers/indexes/isIndexEqual.js +13 -12
  85. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  86. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  87. package/lib/helpers/isBsonType.js +3 -6
  88. package/lib/helpers/isMongooseDocument.js +24 -0
  89. package/lib/helpers/isMongooseObject.js +6 -4
  90. package/lib/helpers/isObject.js +2 -2
  91. package/lib/helpers/isPOJO.js +12 -0
  92. package/lib/helpers/isSimpleValidator.js +2 -2
  93. package/lib/helpers/minimize.js +41 -0
  94. package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
  95. package/lib/helpers/model/applyHooks.js +72 -54
  96. package/lib/helpers/model/applyMethods.js +3 -3
  97. package/lib/helpers/model/applyStaticHooks.js +20 -50
  98. package/lib/helpers/model/castBulkWrite.js +278 -172
  99. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  100. package/lib/helpers/model/discriminator.js +77 -21
  101. package/lib/helpers/omitUndefined.js +20 -0
  102. package/lib/helpers/parallelLimit.js +61 -34
  103. package/lib/helpers/path/setDottedPath.js +1 -1
  104. package/lib/helpers/pathTrie.js +167 -0
  105. package/lib/helpers/pluralize.js +5 -4
  106. package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
  107. package/lib/helpers/populate/assignVals.js +46 -21
  108. package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
  109. package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
  110. package/lib/helpers/populate/getSchemaTypes.js +27 -30
  111. package/lib/helpers/populate/getVirtual.js +31 -0
  112. package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
  113. package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
  114. package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
  115. package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
  116. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  117. package/lib/helpers/populate/splitPopulateQuery.js +81 -0
  118. package/lib/helpers/printJestWarning.js +1 -1
  119. package/lib/helpers/processConnectionOptions.js +7 -2
  120. package/lib/helpers/projection/applyProjection.js +8 -2
  121. package/lib/helpers/projection/hasIncludedChildren.js +1 -1
  122. package/lib/helpers/projection/isExclusive.js +8 -6
  123. package/lib/helpers/projection/isInclusive.js +2 -1
  124. package/lib/helpers/projection/isPathExcluded.js +3 -3
  125. package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
  126. package/lib/helpers/projection/isSubpath.js +1 -1
  127. package/lib/helpers/projection/parseProjection.js +9 -4
  128. package/lib/helpers/query/applyGlobalOption.js +9 -9
  129. package/lib/helpers/query/cast$expr.js +52 -23
  130. package/lib/helpers/query/castFilterPath.js +22 -22
  131. package/lib/helpers/query/castUpdate.js +207 -79
  132. package/lib/helpers/query/cloneMongooseOptions.js +44 -0
  133. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
  134. package/lib/helpers/query/handleImmutable.js +18 -2
  135. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  136. package/lib/helpers/query/sanitizeFilter.js +3 -2
  137. package/lib/helpers/query/selectPopulatedFields.js +13 -0
  138. package/lib/helpers/query/validOps.js +1 -22
  139. package/lib/helpers/schema/applyPlugins.js +2 -2
  140. package/lib/helpers/schema/applyReadConcern.js +20 -0
  141. package/lib/helpers/schema/applyWriteConcern.js +12 -3
  142. package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
  143. package/lib/helpers/schema/getIndexes.js +20 -13
  144. package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
  145. package/lib/helpers/schema/getPath.js +11 -3
  146. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  147. package/lib/helpers/schema/handleIdOption.js +1 -1
  148. package/lib/helpers/schema/idGetter.js +7 -2
  149. package/lib/helpers/schema/merge.js +9 -1
  150. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  151. package/lib/helpers/schematype/handleImmutable.js +1 -1
  152. package/lib/helpers/setDefaultsOnInsert.js +85 -43
  153. package/lib/helpers/symbols.js +4 -4
  154. package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
  155. package/lib/helpers/timestamps/setupTimestamps.js +69 -37
  156. package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
  157. package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
  158. package/lib/helpers/update/castArrayFilters.js +68 -29
  159. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  160. package/lib/helpers/update/modifiedPaths.js +2 -2
  161. package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
  162. package/lib/helpers/updateValidators.js +87 -128
  163. package/lib/index.js +6 -1320
  164. package/lib/internal.js +7 -1
  165. package/lib/model.js +2587 -2618
  166. package/lib/modifiedPathsSnapshot.js +9 -0
  167. package/lib/mongoose.js +1456 -0
  168. package/lib/options/saveOptions.js +2 -0
  169. package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
  170. package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
  171. package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
  172. package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
  173. package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
  174. package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
  175. package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
  176. package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
  177. package/lib/options/schemaSubdocumentOptions.js +89 -0
  178. package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
  179. package/lib/options/schemaUnionOptions.js +32 -0
  180. package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
  181. package/lib/options.js +4 -1
  182. package/lib/plugins/index.js +0 -2
  183. package/lib/plugins/saveSubdocs.js +85 -50
  184. package/lib/plugins/sharding.js +43 -15
  185. package/lib/plugins/trackTransaction.js +46 -34
  186. package/lib/query.js +1844 -1909
  187. package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
  188. package/lib/schema/array.js +229 -169
  189. package/lib/schema/bigint.js +281 -0
  190. package/lib/schema/boolean.js +90 -26
  191. package/lib/schema/buffer.js +119 -50
  192. package/lib/schema/date.js +102 -38
  193. package/lib/schema/decimal128.js +88 -37
  194. package/lib/schema/{documentarray.js → documentArray.js} +259 -151
  195. package/lib/schema/documentArrayElement.js +180 -0
  196. package/lib/schema/double.js +244 -0
  197. package/lib/schema/index.js +12 -19
  198. package/lib/schema/int32.js +288 -0
  199. package/lib/schema/map.js +129 -20
  200. package/lib/schema/mixed.js +40 -26
  201. package/lib/schema/number.js +128 -51
  202. package/lib/schema/{objectid.js → objectId.js} +89 -47
  203. package/lib/schema/operators/exists.js +1 -1
  204. package/lib/schema/operators/geospatial.js +2 -2
  205. package/lib/schema/operators/text.js +4 -4
  206. package/lib/schema/string.js +125 -66
  207. package/lib/schema/subdocument.js +443 -0
  208. package/lib/schema/symbols.js +2 -0
  209. package/lib/schema/union.js +167 -0
  210. package/lib/schema/uuid.js +90 -120
  211. package/lib/schema.js +1267 -388
  212. package/lib/{schematype.js → schemaType.js} +481 -246
  213. package/lib/standardSchema/convertErrorToIssues.js +20 -0
  214. package/lib/{statemachine.js → stateMachine.js} +66 -17
  215. package/lib/tracing.js +38 -0
  216. package/lib/types/array/index.js +13 -10
  217. package/lib/types/array/methods/index.js +243 -63
  218. package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
  219. package/lib/types/buffer.js +31 -14
  220. package/lib/types/decimal128.js +1 -1
  221. package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
  222. package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
  223. package/lib/types/double.js +13 -0
  224. package/lib/types/index.js +5 -2
  225. package/lib/types/map.js +62 -25
  226. package/lib/types/objectid.js +2 -2
  227. package/lib/types/subdocument.js +79 -58
  228. package/lib/types/uuid.js +13 -0
  229. package/lib/utils.js +201 -155
  230. package/lib/{validoptions.js → validOptions.js} +10 -2
  231. package/lib/{virtualtype.js → virtualType.js} +47 -18
  232. package/package.json +75 -92
  233. package/types/aggregate.d.ts +31 -7
  234. package/types/augmentations.d.ts +2 -2
  235. package/types/collection.d.ts +21 -16
  236. package/types/connection.d.ts +82 -27
  237. package/types/cursor.d.ts +15 -10
  238. package/types/document.d.ts +137 -56
  239. package/types/error.d.ts +11 -6
  240. package/types/expressions.d.ts +33 -2
  241. package/types/index.d.ts +805 -190
  242. package/types/indexes.d.ts +85 -13
  243. package/types/inferhydrateddoctype.d.ts +151 -0
  244. package/types/inferrawdoctype.d.ts +201 -0
  245. package/types/inferschematype.d.ts +287 -128
  246. package/types/middlewares.d.ts +50 -7
  247. package/types/models.d.ts +1555 -268
  248. package/types/mongooseoptions.d.ts +56 -7
  249. package/types/pipelinestage.d.ts +42 -3
  250. package/types/populate.d.ts +63 -1
  251. package/types/query.d.ts +592 -255
  252. package/types/schemaoptions.d.ts +78 -12
  253. package/types/schematypes.d.ts +254 -65
  254. package/types/session.d.ts +0 -4
  255. package/types/tracing.d.ts +10 -0
  256. package/types/types.d.ts +25 -8
  257. package/types/utility.d.ts +329 -30
  258. package/types/validation.d.ts +19 -14
  259. package/types/virtuals.d.ts +10 -10
  260. package/.eslintrc.js +0 -232
  261. package/.mocharc.yml +0 -4
  262. package/browser.js +0 -8
  263. package/lgtm.yml +0 -12
  264. package/lib/browser.js +0 -158
  265. package/lib/browserDocument.js +0 -101
  266. package/lib/cursor/ChangeStream.js +0 -154
  267. package/lib/cursor/QueryCursor.js +0 -545
  268. package/lib/document_provider.js +0 -30
  269. package/lib/drivers/browser/ReadPreference.js +0 -7
  270. package/lib/drivers/browser/binary.js +0 -14
  271. package/lib/drivers/browser/decimal128.js +0 -7
  272. package/lib/drivers/browser/index.js +0 -16
  273. package/lib/drivers/browser/objectid.js +0 -29
  274. package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
  275. package/lib/drivers/node-mongodb-native/binary.js +0 -10
  276. package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
  277. package/lib/drivers/node-mongodb-native/objectid.js +0 -16
  278. package/lib/error/disconnected.js +0 -33
  279. package/lib/helpers/printStrictQueryWarning.js +0 -11
  280. package/lib/helpers/promiseOrCallback.js +0 -55
  281. package/lib/helpers/query/applyQueryMiddleware.js +0 -79
  282. package/lib/helpers/query/completeMany.js +0 -52
  283. package/lib/helpers/query/wrapThunk.js +0 -36
  284. package/lib/options/SchemaSubdocumentOptions.js +0 -42
  285. package/lib/options/removeOptions.js +0 -14
  286. package/lib/plugins/removeSubdocs.js +0 -31
  287. package/lib/plugins/validateBeforeSave.js +0 -45
  288. package/lib/promise_provider.js +0 -49
  289. package/lib/schema/DocumentArrayElement.js +0 -100
  290. package/lib/schema/SubdocumentPath.js +0 -369
  291. package/scripts/build-browser.js +0 -18
  292. package/scripts/create-tarball.js +0 -7
  293. package/scripts/generateSearch.js +0 -154
  294. package/scripts/tsc-diagnostics-check.js +0 -15
  295. package/tools/auth.js +0 -31
  296. package/tools/repl.js +0 -35
  297. package/tools/sharded.js +0 -46
  298. package/tsconfig.json +0 -9
  299. /package/lib/{connectionstate.js → connectionState.js} +0 -0
  300. /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
  301. /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
  302. /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
@@ -5,25 +5,29 @@
5
5
  */
6
6
 
7
7
  const MongooseError = require('../error/index');
8
- const SchemaNumberOptions = require('../options/SchemaNumberOptions');
9
- const SchemaType = require('../schematype');
8
+ const SchemaNumberOptions = require('../options/schemaNumberOptions');
9
+ const SchemaType = require('../schemaType');
10
10
  const castNumber = require('../cast/number');
11
11
  const handleBitwiseOperator = require('./operators/bitwise');
12
12
  const utils = require('../utils');
13
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
13
14
 
14
15
  const CastError = SchemaType.CastError;
15
16
 
16
17
  /**
17
18
  * Number SchemaType constructor.
18
19
  *
19
- * @param {String} key
20
- * @param {Object} options
20
+ * @param {string} key
21
+ * @param {object} options
22
+ * @param {object} schemaOptions
23
+ * @param {Schema} parentSchema
21
24
  * @inherits SchemaType
22
25
  * @api public
23
26
  */
24
27
 
25
- function SchemaNumber(key, options) {
26
- SchemaType.call(this, key, options, 'Number');
28
+ function SchemaNumber(key, options, _schemaOptions, parentSchema) {
29
+ this.enumValues = [];
30
+ SchemaType.call(this, key, options, 'Number', parentSchema);
27
31
  }
28
32
 
29
33
  /**
@@ -52,13 +56,13 @@ SchemaNumber.get = SchemaType.get;
52
56
  * #### Example:
53
57
  *
54
58
  * // Make all numbers have option `min` equal to 0.
55
- * mongoose.Schema.Number.set('min', 0);
59
+ * mongoose.Schema.Types.Number.set('min', 0);
56
60
  *
57
61
  * const Order = mongoose.model('Order', new Schema({ amount: Number }));
58
62
  * new Order({ amount: -10 }).validateSync().errors.amount.message; // Path `amount` must be larger than 0.
59
63
  *
60
- * @param {String} option The option you'd like to set the value for
61
- * @param {Any} value value for option
64
+ * @param {string} option The option you'd like to set the value for
65
+ * @param {any} value value for option
62
66
  * @return {undefined}
63
67
  * @function set
64
68
  * @static
@@ -67,6 +71,8 @@ SchemaNumber.get = SchemaType.get;
67
71
 
68
72
  SchemaNumber.set = SchemaType.set;
69
73
 
74
+ SchemaNumber.setters = [];
75
+
70
76
  /*!
71
77
  * ignore
72
78
  */
@@ -90,7 +96,7 @@ SchemaNumber._cast = castNumber;
90
96
  *
91
97
  * @param {Function} caster
92
98
  * @return {Function}
93
- * @function get
99
+ * @function cast
94
100
  * @static
95
101
  * @api public
96
102
  */
@@ -157,9 +163,9 @@ SchemaNumber.checkRequired = SchemaType.checkRequired;
157
163
  /**
158
164
  * Check if the given value satisfies a required validator.
159
165
  *
160
- * @param {Any} value
166
+ * @param {any} value
161
167
  * @param {Document} doc
162
- * @return {Boolean}
168
+ * @return {boolean}
163
169
  * @api public
164
170
  */
165
171
 
@@ -201,10 +207,10 @@ SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) {
201
207
  * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
202
208
  * })
203
209
  *
204
- * @param {Number} value minimum number
205
- * @param {String} [message] optional custom error message
210
+ * @param {number} value minimum number
211
+ * @param {string} [message] optional custom error message
206
212
  * @return {SchemaType} this
207
- * @see Customized Error Messages #error_messages_MongooseError-messages
213
+ * @see Customized Error Messages https://mongoosejs.com/docs/api/error.html#Error.messages
208
214
  * @api public
209
215
  */
210
216
 
@@ -215,9 +221,11 @@ SchemaNumber.prototype.min = function(value, message) {
215
221
  }, this);
216
222
  }
217
223
 
218
- if (value !== null && value !== undefined) {
224
+ if (value != null) {
219
225
  let msg = message || MongooseError.messages.Number.min;
220
- msg = msg.replace(/{MIN}/, value);
226
+ if (typeof msg === 'string') {
227
+ msg = msg.replace(/{MIN}/, value);
228
+ }
221
229
  this.validators.push({
222
230
  validator: this.minValidator = function(v) {
223
231
  return v == null || v >= value;
@@ -255,10 +263,10 @@ SchemaNumber.prototype.min = function(value, message) {
255
263
  * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
256
264
  * })
257
265
  *
258
- * @param {Number} maximum number
259
- * @param {String} [message] optional custom error message
266
+ * @param {number} maximum number
267
+ * @param {string} [message] optional custom error message
260
268
  * @return {SchemaType} this
261
- * @see Customized Error Messages #error_messages_MongooseError-messages
269
+ * @see Customized Error Messages https://mongoosejs.com/docs/api/error.html#Error.messages
262
270
  * @api public
263
271
  */
264
272
 
@@ -269,9 +277,11 @@ SchemaNumber.prototype.max = function(value, message) {
269
277
  }, this);
270
278
  }
271
279
 
272
- if (value !== null && value !== undefined) {
280
+ if (value != null) {
273
281
  let msg = message || MongooseError.messages.Number.max;
274
- msg = msg.replace(/{MAX}/, value);
282
+ if (typeof msg === 'string') {
283
+ msg = msg.replace(/{MAX}/, value);
284
+ }
275
285
  this.validators.push({
276
286
  validator: this.maxValidator = function(v) {
277
287
  return v == null || v <= value;
@@ -300,9 +310,9 @@ SchemaNumber.prototype.max = function(value, message) {
300
310
  * await m.save(); // succeeds
301
311
  *
302
312
  * @param {Array} values allowed values
303
- * @param {String} [message] optional custom error message
313
+ * @param {string} [message] optional custom error message
304
314
  * @return {SchemaType} this
305
- * @see Customized Error Messages #error_messages_MongooseError-messages
315
+ * @see Customized Error Messages https://mongoosejs.com/docs/api/error.html#Error.messages
306
316
  * @api public
307
317
  */
308
318
 
@@ -311,8 +321,14 @@ SchemaNumber.prototype.enum = function(values, message) {
311
321
  this.validators = this.validators.filter(function(v) {
312
322
  return v.validator !== this.enumValidator;
313
323
  }, this);
324
+ this.enumValidator = false;
314
325
  }
315
326
 
327
+ if (values == null || values === false) {
328
+ this.enumValues = [];
329
+ delete this.options.enum;
330
+ return this;
331
+ }
316
332
 
317
333
  if (!Array.isArray(values)) {
318
334
  const isObjectSyntax = utils.isPOJO(values) && values.values != null;
@@ -325,19 +341,44 @@ SchemaNumber.prototype.enum = function(values, message) {
325
341
  }
326
342
 
327
343
  if (utils.isPOJO(values)) {
328
- values = Object.values(values);
344
+ // TypeScript numeric enums produce objects with reverse
345
+ // mappings, e.g. { 0: 'Zero', 1: 'One', Zero: 0, One: 1 }.
346
+ // Object.values on that will yield ['Zero','One',0,1].
347
+ // For Number schema enums we only want the numeric values,
348
+ // otherwise casting the name strings to Number will throw.
349
+ const keys = Object.keys(values).sort();
350
+ const objVals = Object.values(values).sort();
351
+ // If keys and values are equal and half of values are numbers,
352
+ // this is likely a TS enum with reverse mapping, so use only the numbers.
353
+ if (
354
+ keys.length === objVals.length &&
355
+ keys.every((k, i) => k === String(objVals[i])) &&
356
+ objVals.filter(v => typeof v === 'number').length === Math.floor(objVals.length / 2)
357
+ ) {
358
+ values = objVals.filter(v => typeof v === 'number');
359
+ } else {
360
+ // Avoid sorting the values to preserve user-specified order
361
+ values = Object.values(values);
362
+ }
329
363
  }
330
364
  message = message || MongooseError.messages.Number.enum;
331
365
  }
332
366
 
333
367
  message = message == null ? MongooseError.messages.Number.enum : message;
334
368
 
335
- this.enumValidator = v => v == null || values.indexOf(v) !== -1;
369
+ for (const value of values) {
370
+ if (value !== undefined) {
371
+ this.enumValues.push(this.cast(value));
372
+ }
373
+ }
374
+
375
+ const vals = this.enumValues;
376
+ this.enumValidator = v => v == null || vals.indexOf(v) !== -1;
336
377
  this.validators.push({
337
378
  validator: this.enumValidator,
338
379
  message: message,
339
380
  type: 'enum',
340
- enumValues: values
381
+ enumValues: vals
341
382
  });
342
383
 
343
384
  return this;
@@ -346,20 +387,20 @@ SchemaNumber.prototype.enum = function(values, message) {
346
387
  /**
347
388
  * Casts to number
348
389
  *
349
- * @param {Object} value value to cast
390
+ * @param {object} value value to cast
350
391
  * @param {Document} doc document that triggers the casting
351
- * @param {Boolean} init
392
+ * @param {boolean} init
352
393
  * @api private
353
394
  */
354
395
 
355
- SchemaNumber.prototype.cast = function(value, doc, init) {
396
+ SchemaNumber.prototype.cast = function(value, doc, init, prev, options) {
356
397
  if (typeof value !== 'number' && SchemaType._isRef(this, value, doc, init)) {
357
398
  if (value == null || utils.isNonBuiltinObject(value)) {
358
- return this._castRef(value, doc, init);
399
+ return this._castRef(value, doc, init, options);
359
400
  }
360
401
  }
361
402
 
362
- const val = value && typeof value._id !== 'undefined' ?
403
+ const val = value?._id !== undefined ?
363
404
  value._id : // documents
364
405
  value;
365
406
 
@@ -397,40 +438,76 @@ function handleArray(val) {
397
438
  });
398
439
  }
399
440
 
400
- SchemaNumber.prototype.$conditionalHandlers =
401
- utils.options(SchemaType.prototype.$conditionalHandlers, {
402
- $bitsAllClear: handleBitwiseOperator,
403
- $bitsAnyClear: handleBitwiseOperator,
404
- $bitsAllSet: handleBitwiseOperator,
405
- $bitsAnySet: handleBitwiseOperator,
406
- $gt: handleSingle,
407
- $gte: handleSingle,
408
- $lt: handleSingle,
409
- $lte: handleSingle,
410
- $mod: handleArray
411
- });
441
+ const $conditionalHandlers = {
442
+ ...SchemaType.prototype.$conditionalHandlers,
443
+ $bitsAllClear: handleBitwiseOperator,
444
+ $bitsAnyClear: handleBitwiseOperator,
445
+ $bitsAllSet: handleBitwiseOperator,
446
+ $bitsAnySet: handleBitwiseOperator,
447
+ $gt: handleSingle,
448
+ $gte: handleSingle,
449
+ $lt: handleSingle,
450
+ $lte: handleSingle,
451
+ $mod: handleArray
452
+ };
453
+
454
+ /**
455
+ * Contains the handlers for different query operators for this schema type.
456
+ * For example, `$conditionalHandlers.$gte` is the function Mongoose calls to cast `$gte` filter operators.
457
+ *
458
+ * @property $conditionalHandlers
459
+ * @memberOf SchemaNumber
460
+ * @instance
461
+ * @api public
462
+ */
463
+
464
+ Object.defineProperty(SchemaNumber.prototype, '$conditionalHandlers', {
465
+ enumerable: false,
466
+ value: $conditionalHandlers
467
+ });
412
468
 
413
469
  /**
414
470
  * Casts contents for queries.
415
471
  *
416
- * @param {String} $conditional
472
+ * @param {string} $conditional
417
473
  * @param {any} [value]
418
474
  * @api private
419
475
  */
420
476
 
421
- SchemaNumber.prototype.castForQuery = function($conditional, val) {
477
+ SchemaNumber.prototype.castForQuery = function($conditional, val, context) {
422
478
  let handler;
423
- if (arguments.length === 2) {
424
- handler = this.$conditionalHandlers[$conditional];
479
+ if ($conditional != null) {
480
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
425
481
  if (!handler) {
426
- throw new CastError('number', val, this.path, null, this);
482
+ throw new MongooseError('Can\'t use ' + $conditional + ' with Number.');
483
+ }
484
+ return handler.call(this, val, context);
485
+ }
486
+
487
+ try {
488
+ val = this.applySetters(val, context);
489
+ } catch (err) {
490
+ if (err instanceof CastError && err.path === this.path && this.$fullPath != null) {
491
+ err.path = this.$fullPath;
427
492
  }
428
- return handler.call(this, val);
493
+ throw err;
429
494
  }
430
- val = this._castForQuery($conditional);
495
+
431
496
  return val;
432
497
  };
433
498
 
499
+ /**
500
+ * Returns this schema type's representation in a JSON schema.
501
+ *
502
+ * @param {object} [options]
503
+ * @param {boolean} [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
504
+ * @returns {object} JSON schema properties
505
+ */
506
+
507
+ SchemaNumber.prototype.toJSONSchema = function toJSONSchema(options) {
508
+ return this._addJSONSchemaEnum(this._createJSONSchemaTypeDefinition('number', 'number', options));
509
+ };
510
+
434
511
  /*!
435
512
  * Module exports.
436
513
  */
@@ -4,8 +4,8 @@
4
4
 
5
5
  'use strict';
6
6
 
7
- const SchemaObjectIdOptions = require('../options/SchemaObjectIdOptions');
8
- const SchemaType = require('../schematype');
7
+ const SchemaObjectIdOptions = require('../options/schemaObjectIdOptions');
8
+ const SchemaType = require('../schemaType');
9
9
  const castObjectId = require('../cast/objectid');
10
10
  const getConstructorName = require('../helpers/getConstructorName');
11
11
  const oid = require('../types/objectid');
@@ -18,22 +18,24 @@ let Document;
18
18
  /**
19
19
  * ObjectId SchemaType constructor.
20
20
  *
21
- * @param {String} key
22
- * @param {Object} options
21
+ * @param {string} key
22
+ * @param {object} options
23
+ * @param {object} schemaOptions
24
+ * @param {Schema} parentSchema
23
25
  * @inherits SchemaType
24
26
  * @api public
25
27
  */
26
28
 
27
- function ObjectId(key, options) {
29
+ function SchemaObjectId(key, options, _schemaOptions, parentSchema) {
28
30
  const isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key);
29
- const suppressWarning = options && options.suppressWarning;
31
+ const suppressWarning = options?.suppressWarning;
30
32
  if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) {
31
33
  utils.warn('mongoose: To create a new ObjectId please try ' +
32
34
  '`Mongoose.Types.ObjectId` instead of using ' +
33
- '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' +
35
+ '`Mongoose.Schema.Types.ObjectId`. Set the `suppressWarning` option if ' +
34
36
  'you\'re trying to create a hex char path in your schema.');
35
37
  }
36
- SchemaType.call(this, key, options, 'ObjectID');
38
+ SchemaType.call(this, key, options, 'ObjectId', parentSchema);
37
39
  }
38
40
 
39
41
  /**
@@ -42,16 +44,16 @@ function ObjectId(key, options) {
42
44
  *
43
45
  * @api public
44
46
  */
45
- ObjectId.schemaName = 'ObjectId';
47
+ SchemaObjectId.schemaName = 'ObjectId';
46
48
 
47
- ObjectId.defaultOptions = {};
49
+ SchemaObjectId.defaultOptions = {};
48
50
 
49
51
  /*!
50
52
  * Inherits from SchemaType.
51
53
  */
52
- ObjectId.prototype = Object.create(SchemaType.prototype);
53
- ObjectId.prototype.constructor = ObjectId;
54
- ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions;
54
+ SchemaObjectId.prototype = Object.create(SchemaType.prototype);
55
+ SchemaObjectId.prototype.constructor = SchemaObjectId;
56
+ SchemaObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions;
55
57
 
56
58
  /**
57
59
  * Attaches a getter for all ObjectId instances
@@ -71,7 +73,7 @@ ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions;
71
73
  * @api public
72
74
  */
73
75
 
74
- ObjectId.get = SchemaType.get;
76
+ SchemaObjectId.get = SchemaType.get;
75
77
 
76
78
  /**
77
79
  * Sets a default option for all ObjectId instances.
@@ -79,29 +81,31 @@ ObjectId.get = SchemaType.get;
79
81
  * #### Example:
80
82
  *
81
83
  * // Make all object ids have option `required` equal to true.
82
- * mongoose.Schema.ObjectId.set('required', true);
84
+ * mongoose.Schema.Types.ObjectId.set('required', true);
83
85
  *
84
86
  * const Order = mongoose.model('Order', new Schema({ userId: ObjectId }));
85
87
  * new Order({ }).validateSync().errors.userId.message; // Path `userId` is required.
86
88
  *
87
- * @param {String} option The option you'd like to set the value for
88
- * @param {Any} value value for option
89
+ * @param {string} option The option you'd like to set the value for
90
+ * @param {any} value value for option
89
91
  * @return {undefined}
90
92
  * @function set
91
93
  * @static
92
94
  * @api public
93
95
  */
94
96
 
95
- ObjectId.set = SchemaType.set;
97
+ SchemaObjectId.set = SchemaType.set;
98
+
99
+ SchemaObjectId.setters = [];
96
100
 
97
101
  /**
98
102
  * Adds an auto-generated ObjectId default if turnOn is true.
99
- * @param {Boolean} turnOn auto generated ObjectId defaults
103
+ * @param {boolean} turnOn auto generated ObjectId defaults
100
104
  * @api public
101
105
  * @return {SchemaType} this
102
106
  */
103
107
 
104
- ObjectId.prototype.auto = function(turnOn) {
108
+ SchemaObjectId.prototype.auto = function(turnOn) {
105
109
  if (turnOn) {
106
110
  this.default(defaultId);
107
111
  this.set(resetId);
@@ -114,13 +118,13 @@ ObjectId.prototype.auto = function(turnOn) {
114
118
  * ignore
115
119
  */
116
120
 
117
- ObjectId._checkRequired = v => isBsonType(v, 'ObjectID');
121
+ SchemaObjectId._checkRequired = v => isBsonType(v, 'ObjectId');
118
122
 
119
123
  /*!
120
124
  * ignore
121
125
  */
122
126
 
123
- ObjectId._cast = castObjectId;
127
+ SchemaObjectId._cast = castObjectId;
124
128
 
125
129
  /**
126
130
  * Get/set the function used to cast arbitrary values to objectids.
@@ -140,12 +144,12 @@ ObjectId._cast = castObjectId;
140
144
  *
141
145
  * @param {Function} caster
142
146
  * @return {Function}
143
- * @function get
147
+ * @function cast
144
148
  * @static
145
149
  * @api public
146
150
  */
147
151
 
148
- ObjectId.cast = function cast(caster) {
152
+ SchemaObjectId.cast = function cast(caster) {
149
153
  if (arguments.length === 0) {
150
154
  return this._cast;
151
155
  }
@@ -161,8 +165,8 @@ ObjectId.cast = function cast(caster) {
161
165
  * ignore
162
166
  */
163
167
 
164
- ObjectId._defaultCaster = v => {
165
- if (!(isBsonType(v, 'ObjectID'))) {
168
+ SchemaObjectId._defaultCaster = v => {
169
+ if (!(isBsonType(v, 'ObjectId'))) {
166
170
  throw new Error(v + ' is not an instance of ObjectId');
167
171
  }
168
172
  return v;
@@ -187,18 +191,18 @@ ObjectId._defaultCaster = v => {
187
191
  * @api public
188
192
  */
189
193
 
190
- ObjectId.checkRequired = SchemaType.checkRequired;
194
+ SchemaObjectId.checkRequired = SchemaType.checkRequired;
191
195
 
192
196
  /**
193
197
  * Check if the given value satisfies a required validator.
194
198
  *
195
- * @param {Any} value
199
+ * @param {any} value
196
200
  * @param {Document} doc
197
- * @return {Boolean}
201
+ * @return {boolean}
198
202
  * @api public
199
203
  */
200
204
 
201
- ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
205
+ SchemaObjectId.prototype.checkRequired = function checkRequired(value, doc) {
202
206
  if (SchemaType._isRef(this, value, doc, true)) {
203
207
  return !!value;
204
208
  }
@@ -207,7 +211,7 @@ ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
207
211
  // plugins like mongoose-float use `inherits()` for pre-ES6.
208
212
  const _checkRequired = typeof this.constructor.checkRequired === 'function' ?
209
213
  this.constructor.checkRequired() :
210
- ObjectId.checkRequired();
214
+ SchemaObjectId.checkRequired();
211
215
 
212
216
  return _checkRequired(value);
213
217
  };
@@ -215,21 +219,21 @@ ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
215
219
  /**
216
220
  * Casts to ObjectId
217
221
  *
218
- * @param {Object} value
219
- * @param {Object} doc
220
- * @param {Boolean} init whether this is an initialization cast
222
+ * @param {object} value
223
+ * @param {object} doc
224
+ * @param {boolean} init whether this is an initialization cast
221
225
  * @api private
222
226
  */
223
227
 
224
- ObjectId.prototype.cast = function(value, doc, init) {
225
- if (!(isBsonType(value, 'ObjectID')) && SchemaType._isRef(this, value, doc, init)) {
228
+ SchemaObjectId.prototype.cast = function(value, doc, init, prev, options) {
229
+ if (!(isBsonType(value, 'ObjectId')) && SchemaType._isRef(this, value, doc, init)) {
226
230
  // wait! we may need to cast this to a document
227
231
  if ((getConstructorName(value) || '').toLowerCase() === 'objectid') {
228
232
  return new oid(value.toHexString());
229
233
  }
230
234
 
231
235
  if (value == null || utils.isNonBuiltinObject(value)) {
232
- return this._castRef(value, doc, init);
236
+ return this._castRef(value, doc, init, options);
233
237
  }
234
238
  }
235
239
 
@@ -239,7 +243,7 @@ ObjectId.prototype.cast = function(value, doc, init) {
239
243
  } else if (typeof this.constructor.cast === 'function') {
240
244
  castObjectId = this.constructor.cast();
241
245
  } else {
242
- castObjectId = ObjectId.cast();
246
+ castObjectId = SchemaObjectId.cast();
243
247
  }
244
248
 
245
249
  try {
@@ -257,13 +261,28 @@ function handleSingle(val) {
257
261
  return this.cast(val);
258
262
  }
259
263
 
260
- ObjectId.prototype.$conditionalHandlers =
261
- utils.options(SchemaType.prototype.$conditionalHandlers, {
262
- $gt: handleSingle,
263
- $gte: handleSingle,
264
- $lt: handleSingle,
265
- $lte: handleSingle
266
- });
264
+ const $conditionalHandlers = {
265
+ ...SchemaType.prototype.$conditionalHandlers,
266
+ $gt: handleSingle,
267
+ $gte: handleSingle,
268
+ $lt: handleSingle,
269
+ $lte: handleSingle
270
+ };
271
+
272
+ /**
273
+ * Contains the handlers for different query operators for this schema type.
274
+ * For example, `$conditionalHandlers.$in` is the function Mongoose calls to cast `$in` filter operators.
275
+ *
276
+ * @property $conditionalHandlers
277
+ * @memberOf SchemaObjectId
278
+ * @instance
279
+ * @api public
280
+ */
281
+
282
+ Object.defineProperty(SchemaObjectId.prototype, '$conditionalHandlers', {
283
+ enumerable: false,
284
+ value: $conditionalHandlers
285
+ });
267
286
 
268
287
  /*!
269
288
  * ignore
@@ -276,7 +295,7 @@ function defaultId() {
276
295
  defaultId.$runBeforeSetters = true;
277
296
 
278
297
  function resetId(v) {
279
- Document || (Document = require('./../document'));
298
+ Document || (Document = require('../document'));
280
299
 
281
300
  if (this instanceof Document) {
282
301
  if (v === void 0) {
@@ -288,8 +307,31 @@ function resetId(v) {
288
307
  return v;
289
308
  }
290
309
 
310
+ /**
311
+ * Returns this schema type's representation in a JSON schema.
312
+ *
313
+ * @param {object} [options]
314
+ * @param {boolean} [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
315
+ * @returns {object} JSON schema properties
316
+ * @api public
317
+ */
318
+
319
+ SchemaObjectId.prototype.toJSONSchema = function toJSONSchema(options) {
320
+ const jsonSchema = this._createJSONSchemaTypeDefinition('string', 'objectId', options);
321
+ // `bsonType: 'objectId'` already validates ObjectIds, so the regex is only useful
322
+ // for the portable `type: 'string'` representation (e.g. for ajv, zod, etc.)
323
+ if (!options?.useBsonType) {
324
+ jsonSchema.pattern = '^[A-Fa-f0-9]{24}$';
325
+ }
326
+ return jsonSchema;
327
+ };
328
+
329
+ SchemaObjectId.prototype.autoEncryptionType = function autoEncryptionType() {
330
+ return 'objectId';
331
+ };
332
+
291
333
  /*!
292
334
  * Module exports.
293
335
  */
294
336
 
295
- module.exports = ObjectId;
337
+ module.exports = SchemaObjectId;
@@ -7,6 +7,6 @@ const castBoolean = require('../../cast/boolean');
7
7
  */
8
8
 
9
9
  module.exports = function(val) {
10
- const path = this != null ? this.path : null;
10
+ const path = this?.path ?? null;
11
11
  return castBoolean(val, path);
12
12
  };
@@ -25,7 +25,7 @@ function cast$near(val) {
25
25
 
26
26
  _castMinMaxDistance(this, val);
27
27
 
28
- if (val && val.$geometry) {
28
+ if (val?.$geometry) {
29
29
  return cast$geometry(val, this);
30
30
  }
31
31
 
@@ -34,7 +34,7 @@ function cast$near(val) {
34
34
  'with a $geometry property');
35
35
  }
36
36
 
37
- return SchemaArray.prototype.castForQuery.call(this, val);
37
+ return SchemaArray.prototype.castForQuery.call(this, null, val);
38
38
  }
39
39
 
40
40
  function cast$geometry(val, self) {
@@ -8,9 +8,9 @@ const castString = require('../../cast/string');
8
8
  * Casts val to an object suitable for `$text`. Throws an error if the object
9
9
  * can't be casted.
10
10
  *
11
- * @param {Any} val value to cast
12
- * @param {String} [path] path to associate with any errors that occured
13
- * @return {Object} casted object
11
+ * @param {any} val value to cast
12
+ * @param {string} [path] path to associate with any errors that occurred
13
+ * @return {object} casted object
14
14
  * @see https://www.mongodb.com/docs/manual/reference/operator/query/text/
15
15
  * @api private
16
16
  */
@@ -28,7 +28,7 @@ module.exports = function castTextSearch(val, path) {
28
28
  }
29
29
  if (val.$caseSensitive != null) {
30
30
  val.$caseSensitive = castBoolean(val.$caseSensitive,
31
- path + '.$castSensitive');
31
+ path + '.$caseSensitive');
32
32
  }
33
33
  if (val.$diacriticSensitive != null) {
34
34
  val.$diacriticSensitive = castBoolean(val.$diacriticSensitive,