@datanimbus/mongoose 6.13.13 → 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
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ const { Long } = require('mongodb/lib/bson');
4
+
5
+ /**
6
+ * Given a value, cast it to a BigInt, or throw an `Error` if the value
7
+ * cannot be casted. `null` and `undefined` are considered valid.
8
+ *
9
+ * @param {any} value
10
+ * @return {bigint|null|undefined}
11
+ * @throws {Error} if `value` is not one of the allowed values
12
+ * @api private
13
+ */
14
+
15
+ const MAX_BIGINT = 9223372036854775807n;
16
+ const MIN_BIGINT = -9223372036854775808n;
17
+ const ERROR_MESSAGE = `Mongoose only supports BigInts between ${MIN_BIGINT} and ${MAX_BIGINT} because MongoDB does not support arbitrary precision integers`;
18
+
19
+ module.exports = function castBigInt(val) {
20
+ if (val == null) {
21
+ return val;
22
+ }
23
+ if (val === '') {
24
+ return null;
25
+ }
26
+ if (typeof val === 'bigint') {
27
+ if (val > MAX_BIGINT || val < MIN_BIGINT) {
28
+ throw new Error(ERROR_MESSAGE);
29
+ }
30
+ return val;
31
+ }
32
+
33
+ if (val instanceof Long) {
34
+ return val.toBigInt();
35
+ }
36
+
37
+ if (typeof val === 'string' || typeof val === 'number') {
38
+ val = BigInt(val);
39
+ if (val > MAX_BIGINT || val < MIN_BIGINT) {
40
+ throw new Error(ERROR_MESSAGE);
41
+ }
42
+ return val;
43
+ }
44
+
45
+ throw new Error(`Cannot convert value to BigInt: "${val}"`);
46
+ };
@@ -6,9 +6,9 @@ const CastError = require('../error/cast');
6
6
  * Given a value, cast it to a boolean, or throw a `CastError` if the value
7
7
  * cannot be casted. `null` and `undefined` are considered valid.
8
8
  *
9
- * @param {Any} value
10
- * @param {String} [path] optional the path to set on the CastError
11
- * @return {Boolean|null|undefined}
9
+ * @param {any} value
10
+ * @param {string} [path] optional the path to set on the CastError
11
+ * @return {boolean|null|undefined}
12
12
  * @throws {CastError} if `value` is not one of the allowed values
13
13
  * @api private
14
14
  */
@@ -20,7 +20,10 @@ module.exports = function castDecimal128(value) {
20
20
  return Decimal128Type.fromString(value);
21
21
  }
22
22
 
23
- if (Buffer.isBuffer(value)) {
23
+ if (typeof Buffer === 'function' && Buffer.isBuffer(value)) {
24
+ return new Decimal128Type(value);
25
+ }
26
+ if (typeof Uint8Array === 'function' && value instanceof Uint8Array) {
24
27
  return new Decimal128Type(value);
25
28
  }
26
29
 
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ const assert = require('assert');
4
+ const BSON = require('mongodb/lib/bson');
5
+ const isBsonType = require('../helpers/isBsonType');
6
+
7
+ /**
8
+ * Given a value, cast it to a IEEE 754-2008 floating point, or throw an `Error` if the value
9
+ * cannot be casted. `null`, `undefined`, and `NaN` are considered valid inputs.
10
+ *
11
+ * @param {any} value
12
+ * @return {number}
13
+ * @throws {Error} if `value` does not represent a IEEE 754-2008 floating point. If casting from a string, see [BSON Double.fromString API documentation](https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Double.html#fromString)
14
+ * @api private
15
+ */
16
+
17
+ module.exports = function castDouble(val) {
18
+ if (val == null || val === '') {
19
+ return null;
20
+ }
21
+
22
+ let coercedVal;
23
+ if (isBsonType(val, 'Long')) {
24
+ coercedVal = val.toNumber();
25
+ } else if (typeof val === 'string') {
26
+ try {
27
+ coercedVal = BSON.Double.fromString(val);
28
+ return coercedVal;
29
+ } catch {
30
+ assert.ok(false);
31
+ }
32
+ } else if (typeof val === 'object') {
33
+ if (Array.isArray(val)) {
34
+ // `[5].valueOf()` returns the array itself, so without this guard a
35
+ // single-element or empty array would fall through to `Number(tempVal)`
36
+ // below and silently coerce instead of throwing.
37
+ assert.ok(false);
38
+ }
39
+ const tempVal = val.valueOf() ?? val.toString();
40
+ // ex: { a: 'im an object, valueOf: () => 'helloworld' } // throw an error
41
+ if (typeof tempVal === 'string') {
42
+ try {
43
+ coercedVal = BSON.Double.fromString(tempVal);
44
+ return coercedVal;
45
+ } catch {
46
+ assert.ok(false);
47
+ }
48
+ } else {
49
+ coercedVal = Number(tempVal);
50
+ }
51
+ } else {
52
+ coercedVal = Number(val);
53
+ }
54
+
55
+ return new BSON.Double(coercedVal);
56
+ };
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ const isBsonType = require('../helpers/isBsonType');
4
+ const assert = require('assert');
5
+
6
+ /**
7
+ * Given a value, cast it to a Int32, or throw an `Error` if the value
8
+ * cannot be casted. `null` and `undefined` are considered valid.
9
+ *
10
+ * @param {any} value
11
+ * @return {number}
12
+ * @throws {Error} if `value` does not represent an integer, or is outside the bounds of an 32-bit integer.
13
+ * @api private
14
+ */
15
+
16
+ module.exports = function castInt32(val) {
17
+ if (val == null) {
18
+ return val;
19
+ }
20
+ if (val === '') {
21
+ return null;
22
+ }
23
+ if (Array.isArray(val)) {
24
+ // `Number([5])` is `5` and `Number([])` is `0`, so without this guard a
25
+ // single-element or empty array would silently coerce instead of throwing,
26
+ // unlike every other array input and unlike `castNumber()`'s own guard.
27
+ assert.ok(false);
28
+ }
29
+
30
+ const coercedVal = isBsonType(val, 'Long') ? val.toNumber() : Number(val);
31
+
32
+ const INT32_MAX = 0x7FFFFFFF;
33
+ const INT32_MIN = -0x80000000;
34
+
35
+ if (coercedVal === (coercedVal | 0) &&
36
+ coercedVal >= INT32_MIN &&
37
+ coercedVal <= INT32_MAX
38
+ ) {
39
+ return coercedVal;
40
+ }
41
+ assert.ok(false);
42
+ };
@@ -1,13 +1,11 @@
1
1
  'use strict';
2
2
 
3
- const assert = require('assert');
4
-
5
3
  /**
6
4
  * Given a value, cast it to a number, or throw an `Error` if the value
7
5
  * cannot be casted. `null` and `undefined` are considered valid.
8
6
  *
9
- * @param {Any} value
10
- * @return {Number}
7
+ * @param {any} value
8
+ * @return {number}
11
9
  * @throws {Error} if `value` is not one of the allowed values
12
10
  * @api private
13
11
  */
@@ -24,7 +22,9 @@ module.exports = function castNumber(val) {
24
22
  val = Number(val);
25
23
  }
26
24
 
27
- assert.ok(!isNaN(val));
25
+ if (isNaN(val)) {
26
+ throw new Error('Cast to Number failed: value is not a valid number');
27
+ }
28
28
  if (val instanceof Number) {
29
29
  return val.valueOf();
30
30
  }
@@ -38,5 +38,5 @@ module.exports = function castNumber(val) {
38
38
  return Number(val);
39
39
  }
40
40
 
41
- assert.ok(false);
41
+ throw new Error('Cast to Number failed: value is not a valid number');
42
42
  };
@@ -1,19 +1,19 @@
1
1
  'use strict';
2
2
 
3
3
  const isBsonType = require('../helpers/isBsonType');
4
- const ObjectId = require('../driver').get().ObjectId;
4
+ const ObjectId = require('../types/objectid');
5
5
 
6
6
  module.exports = function castObjectId(value) {
7
7
  if (value == null) {
8
8
  return value;
9
9
  }
10
10
 
11
- if (isBsonType(value, 'ObjectID')) {
11
+ if (isBsonType(value, 'ObjectId')) {
12
12
  return value;
13
13
  }
14
14
 
15
15
  if (value._id) {
16
- if (isBsonType(value._id, 'ObjectID')) {
16
+ if (isBsonType(value._id, 'ObjectId')) {
17
17
  return value._id;
18
18
  }
19
19
  if (value._id.toString instanceof Function) {
@@ -6,8 +6,8 @@ const CastError = require('../error/cast');
6
6
  * Given a value, cast it to a string, or throw a `CastError` if the value
7
7
  * cannot be casted. `null` and `undefined` are considered valid.
8
8
  *
9
- * @param {Any} value
10
- * @param {String} [path] optional the path to set on the CastError
9
+ * @param {any} value
10
+ * @param {string} [path] optional the path to set on the CastError
11
11
  * @return {string|null|undefined}
12
12
  * @throws {CastError}
13
13
  * @api private
@@ -20,7 +20,7 @@ module.exports = function castString(value, path) {
20
20
  }
21
21
 
22
22
  // handle documents being passed
23
- if (value._id && typeof value._id === 'string') {
23
+ if (typeof value?._id === 'string') {
24
24
  return value._id;
25
25
  }
26
26
 
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ const UUID = require('mongodb/lib/bson').UUID;
4
+
5
+ const UUID_FORMAT = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i;
6
+
7
+ module.exports = function castUUID(value) {
8
+ if (value == null) {
9
+ return value;
10
+ }
11
+
12
+ if (value instanceof UUID) {
13
+ return value;
14
+ }
15
+ if (typeof value === 'string') {
16
+ if (UUID_FORMAT.test(value)) {
17
+ return new UUID(value);
18
+ } else {
19
+ throw new Error(`"${value}" is not a valid UUID string`);
20
+ }
21
+ }
22
+
23
+ // Re: gh-647 and gh-3030, we're ok with casting using `toString()`
24
+ // **unless** its the default Object.toString, because "[object Object]"
25
+ // doesn't really qualify as useful data
26
+ if (value.toString && value.toString !== Object.prototype.toString) {
27
+ if (UUID_FORMAT.test(value.toString())) {
28
+ return new UUID(value.toString());
29
+ }
30
+ }
31
+
32
+ throw new Error(`"${value}" cannot be casted to a UUID`);
33
+ };
34
+
35
+ module.exports.UUID_FORMAT = UUID_FORMAT;
package/lib/cast.js CHANGED
@@ -12,12 +12,15 @@ const cast$expr = require('./helpers/query/cast$expr');
12
12
  const castString = require('./cast/string');
13
13
  const castTextSearch = require('./schema/operators/text');
14
14
  const get = require('./helpers/get');
15
- const getConstructorName = require('./helpers/getConstructorName');
15
+ const getDiscriminatorValueFromFilter = require('./helpers/discriminator/getDiscriminatorValueFromFilter');
16
+ const getOwnProperty = require('./helpers/getOwnProperty');
16
17
  const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchemaDiscriminatorByValue');
17
18
  const isOperator = require('./helpers/query/isOperator');
19
+ const { logicalOperators } = require('./filters/operators');
18
20
  const util = require('util');
19
21
  const isObject = require('./helpers/isObject');
20
22
  const isMongooseObject = require('./helpers/isMongooseObject');
23
+ const utils = require('./utils');
21
24
 
22
25
  const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon'];
23
26
 
@@ -25,26 +28,27 @@ const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon'];
25
28
  * Handles internal casting for query filters.
26
29
  *
27
30
  * @param {Schema} schema
28
- * @param {Object} obj Object to cast
29
- * @param {Object} [options] the query options
30
- * @param {Boolean|"throw"} [options.strict] Wheter to enable all strict options
31
- * @param {Boolean|"throw"} [options.strictQuery] Enable strict Queries
32
- * @param {Boolean} [options.upsert]
33
- * @param {Boolean} [options.sanitizeFilter] avoid adding implicit query selectors ($in)
31
+ * @param {object} obj Object to cast
32
+ * @param {object} [options] the query options
33
+ * @param {boolean|"throw"} [options.strict] Whether to enable all strict options
34
+ * @param {boolean|"throw"} [options.strictQuery] Enable strict Queries
35
+ * @param {boolean} [options.sanitizeFilter] avoid adding implicit query selectors ($in)
36
+ * @param {boolean} [options.upsert]
34
37
  * @param {Query} [context] passed to setters
35
38
  * @api private
36
39
  */
37
40
  module.exports = function cast(schema, obj, options, context) {
38
41
  if (Array.isArray(obj)) {
39
- throw new Error('Query filter must be an object, got an array ', util.inspect(obj));
42
+ throw new Error('Query filter must be an object, got an array ' + util.inspect(obj));
40
43
  }
41
44
 
42
45
  if (obj == null) {
43
46
  return obj;
44
47
  }
45
48
 
46
- if (schema != null && schema.discriminators != null && obj[schema.options.discriminatorKey] != null) {
47
- schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema;
49
+ if (schema?.discriminators != null && obj[schema.options.discriminatorKey] != null) {
50
+ const discriminatorValue = getDiscriminatorValueFromFilter(obj[schema.options.discriminatorKey]);
51
+ schema = getSchemaDiscriminatorByValue(schema, discriminatorValue) || schema;
48
52
  }
49
53
 
50
54
  const paths = Object.keys(obj);
@@ -63,7 +67,7 @@ module.exports = function cast(schema, obj, options, context) {
63
67
  path = paths[i];
64
68
  val = obj[path];
65
69
 
66
- if (path === '$or' || path === '$nor' || path === '$and') {
70
+ if (logicalOperators.has(path)) {
67
71
  if (!Array.isArray(val)) {
68
72
  throw new CastError('Array', val, path);
69
73
  }
@@ -71,10 +75,16 @@ module.exports = function cast(schema, obj, options, context) {
71
75
  if (val[k] == null || typeof val[k] !== 'object') {
72
76
  throw new CastError('Object', val[k], path + '.' + k);
73
77
  }
74
-
75
78
  const beforeCastKeysLength = Object.keys(val[k]).length;
76
- val[k] = cast(schema, val[k], options, context);
77
- if (Object.keys(val[k]).length === 0 && beforeCastKeysLength !== 0) {
79
+ const discriminatorValue = val[k][schema.options.discriminatorKey];
80
+ if (discriminatorValue == null) {
81
+ val[k] = cast(schema, val[k], options, context);
82
+ } else {
83
+ const discriminatorSchema = getSchemaDiscriminatorByValue(context.schema, discriminatorValue);
84
+ val[k] = cast(discriminatorSchema ? discriminatorSchema : schema, val[k], options, context);
85
+ }
86
+
87
+ if (utils.hasOwnKeys(val[k]) === false && beforeCastKeysLength !== 0) {
78
88
  val.splice(k, 1);
79
89
  }
80
90
  }
@@ -102,7 +112,7 @@ module.exports = function cast(schema, obj, options, context) {
102
112
  val = cast(schema, val, options, context);
103
113
  } else if (path === '$text') {
104
114
  val = castTextSearch(val, path);
105
- } else if (path === '$comment' && !schema.paths.hasOwnProperty('$comment')) {
115
+ } else if (path === '$comment' && !Object.hasOwn(schema.paths, '$comment')) {
106
116
  val = castString(val, path);
107
117
  obj[path] = val;
108
118
  } else if (isOperator(path)) {
@@ -126,22 +136,17 @@ module.exports = function cast(schema, obj, options, context) {
126
136
  const pathFirstHalf = split.slice(0, j).join('.');
127
137
  const pathLastHalf = split.slice(j).join('.');
128
138
  const _schematype = schema.path(pathFirstHalf);
129
- const discriminatorKey = _schematype &&
130
- _schematype.schema &&
131
- _schematype.schema.options &&
132
- _schematype.schema.options.discriminatorKey;
139
+ const discriminatorKey = _schematype?.schema?.options?.discriminatorKey;
133
140
 
134
141
  // gh-6027: if we haven't found the schematype but this path is
135
142
  // underneath an embedded discriminator and the embedded discriminator
136
143
  // key is in the query, use the embedded discriminator schema
137
- if (_schematype != null &&
138
- (_schematype.schema && _schematype.schema.discriminators) != null &&
144
+ if (_schematype?.schema?.discriminators != null &&
139
145
  discriminatorKey != null &&
140
146
  pathLastHalf !== discriminatorKey) {
141
- const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey);
142
- const discriminator = discriminatorVal != null ?
143
- getDiscriminatorByKey(_schematype.schema.discriminators, discriminatorVal) :
144
- null;
147
+ const discriminatorVal = getDiscriminatorValueFromFilter(get(obj, pathFirstHalf + '.' + discriminatorKey));
148
+ const discriminators = _schematype.schema.discriminators;
149
+ const discriminator = typeof discriminatorVal === 'string' ? getDiscriminatorByKey(discriminators, discriminatorVal) : null;
145
150
  if (discriminator != null) {
146
151
  schematype = discriminator.path(pathLastHalf);
147
152
  }
@@ -169,12 +174,12 @@ module.exports = function cast(schema, obj, options, context) {
169
174
  // If a substring of the input path resolves to an actual real path...
170
175
  if (schematype) {
171
176
  // Apply the casting; similar code for $elemMatch in schema/array.js
172
- if (schematype.caster && schematype.caster.schema) {
177
+ if (schematype.schema) {
173
178
  remainingConds = {};
174
179
  pathLastHalf = split.slice(j).join('.');
175
180
  remainingConds[pathLastHalf] = val;
176
181
 
177
- const ret = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf];
182
+ const ret = cast(schematype.schema, remainingConds, options, context)[pathLastHalf];
178
183
  if (ret === void 0) {
179
184
  delete obj[path];
180
185
  } else {
@@ -204,20 +209,22 @@ module.exports = function cast(schema, obj, options, context) {
204
209
  }
205
210
 
206
211
  if (geo) {
207
- const numbertype = new Types.Number('__QueryCasting__');
212
+ const numbertype = new Types.Number('__QueryCasting__', null, null, schema);
208
213
  let value = val[geo];
209
214
 
210
215
  if (val.$maxDistance != null) {
211
- val.$maxDistance = numbertype.castForQueryWrapper({
212
- val: val.$maxDistance,
213
- context: context
214
- });
216
+ val.$maxDistance = numbertype.castForQuery(
217
+ null,
218
+ val.$maxDistance,
219
+ context
220
+ );
215
221
  }
216
222
  if (val.$minDistance != null) {
217
- val.$minDistance = numbertype.castForQueryWrapper({
218
- val: val.$minDistance,
219
- context: context
220
- });
223
+ val.$minDistance = numbertype.castForQuery(
224
+ null,
225
+ val.$minDistance,
226
+ context
227
+ );
221
228
  }
222
229
 
223
230
  if (geo === '$within') {
@@ -239,16 +246,18 @@ module.exports = function cast(schema, obj, options, context) {
239
246
  value.$geometry && typeof value.$geometry.type === 'string' &&
240
247
  Array.isArray(value.$geometry.coordinates)) {
241
248
  if (value.$maxDistance != null) {
242
- value.$maxDistance = numbertype.castForQueryWrapper({
243
- val: value.$maxDistance,
244
- context: context
245
- });
249
+ value.$maxDistance = numbertype.castForQuery(
250
+ null,
251
+ value.$maxDistance,
252
+ context
253
+ );
246
254
  }
247
255
  if (value.$minDistance != null) {
248
- value.$minDistance = numbertype.castForQueryWrapper({
249
- val: value.$minDistance,
250
- context: context
251
- });
256
+ value.$minDistance = numbertype.castForQuery(
257
+ null,
258
+ value.$minDistance,
259
+ context
260
+ );
252
261
  }
253
262
  if (isMongooseObject(value.$geometry)) {
254
263
  value.$geometry = value.$geometry.toObject({
@@ -282,7 +291,7 @@ module.exports = function cast(schema, obj, options, context) {
282
291
  }
283
292
  }
284
293
 
285
- if (schema.nested[path]) {
294
+ if (getOwnProperty(schema.nested, path)) {
286
295
  continue;
287
296
  }
288
297
 
@@ -302,51 +311,61 @@ module.exports = function cast(schema, obj, options, context) {
302
311
  }
303
312
  } else if (val == null) {
304
313
  continue;
305
- } else if (getConstructorName(val) === 'Object') {
314
+ } else if (utils.isPOJO(val)) {
306
315
  any$conditionals = Object.keys(val).some(isOperator);
307
316
 
308
317
  if (!any$conditionals) {
309
- obj[path] = schematype.castForQueryWrapper({
310
- val: val,
311
- context: context
312
- });
318
+ obj[path] = schematype.castForQuery(
319
+ null,
320
+ val,
321
+ context
322
+ );
313
323
  } else {
314
324
  const ks = Object.keys(val);
315
325
  let $cond;
316
-
317
326
  let k = ks.length;
318
327
 
319
328
  while (k--) {
320
329
  $cond = ks[k];
321
330
  nested = val[$cond];
322
-
323
- if ($cond === '$not') {
331
+ if ($cond === '$elemMatch') {
332
+ if (nested && schematype?.schema != null) {
333
+ cast(schematype.schema, nested, options, context);
334
+ } else if (nested && schematype?.$isMongooseArray) {
335
+ val[$cond] = schematype.castForQuery(
336
+ $cond,
337
+ nested,
338
+ context
339
+ );
340
+ }
341
+ } else if ($cond === '$not') {
324
342
  if (nested && schematype) {
325
343
  _keys = Object.keys(nested);
326
344
  if (_keys.length && isOperator(_keys[0])) {
327
345
  for (const key in nested) {
328
- nested[key] = schematype.castForQueryWrapper({
329
- $conditional: key,
330
- val: nested[key],
331
- context: context
332
- });
346
+ nested[key] = schematype.castForQuery(
347
+ key,
348
+ nested[key],
349
+ context
350
+ );
333
351
  }
334
352
  } else {
335
- val[$cond] = schematype.castForQueryWrapper({
336
- $conditional: $cond,
337
- val: nested,
338
- context: context
339
- });
353
+ val[$cond] = schematype.castForQuery(
354
+ $cond,
355
+ nested,
356
+ context
357
+ );
340
358
  }
341
359
  continue;
342
360
  }
343
361
  } else {
344
- val[$cond] = schematype.castForQueryWrapper({
345
- $conditional: $cond,
346
- val: nested,
347
- context: context
348
- });
362
+ val[$cond] = schematype.castForQuery(
363
+ $cond,
364
+ nested,
365
+ context
366
+ );
349
367
  }
368
+
350
369
  }
351
370
  }
352
371
  } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1 && !options.sanitizeFilter) {
@@ -354,18 +373,20 @@ module.exports = function cast(schema, obj, options, context) {
354
373
  const valuesArray = val;
355
374
 
356
375
  for (const _val of valuesArray) {
357
- casted.push(schematype.castForQueryWrapper({
358
- val: _val,
359
- context: context
360
- }));
376
+ casted.push(schematype.castForQuery(
377
+ null,
378
+ _val,
379
+ context
380
+ ));
361
381
  }
362
382
 
363
383
  obj[path] = { $in: casted };
364
384
  } else {
365
- obj[path] = schematype.castForQueryWrapper({
366
- val: val,
367
- context: context
368
- });
385
+ obj[path] = schematype.castForQuery(
386
+ null,
387
+ val,
388
+ context
389
+ );
369
390
  }
370
391
  }
371
392
  }
@@ -379,7 +400,7 @@ function _cast(val, numbertype, context) {
379
400
  if (Array.isArray(item) || isObject(item)) {
380
401
  return _cast(item, numbertype, context);
381
402
  }
382
- val[i] = numbertype.castForQueryWrapper({ val: item, context: context });
403
+ val[i] = numbertype.castForQuery(null, item, context);
383
404
  });
384
405
  } else {
385
406
  const nearKeys = Object.keys(val);
@@ -391,7 +412,7 @@ function _cast(val, numbertype, context) {
391
412
  _cast(item, numbertype, context);
392
413
  val[nkey] = item;
393
414
  } else {
394
- val[nkey] = numbertype.castForQuery({ val: item, context: context });
415
+ val[nkey] = numbertype.castForQuery(null, item, context);
395
416
  }
396
417
  }
397
418
  }
@@ -401,27 +422,14 @@ function getStrictQuery(queryOptions, schemaUserProvidedOptions, schemaOptions,
401
422
  if ('strictQuery' in queryOptions) {
402
423
  return queryOptions.strictQuery;
403
424
  }
404
- if ('strict' in queryOptions) {
405
- return queryOptions.strict;
406
- }
407
425
  if ('strictQuery' in schemaUserProvidedOptions) {
408
426
  return schemaUserProvidedOptions.strictQuery;
409
427
  }
410
- if ('strict' in schemaUserProvidedOptions) {
411
- return schemaUserProvidedOptions.strict;
412
- }
413
- const mongooseOptions = context &&
414
- context.mongooseCollection &&
415
- context.mongooseCollection.conn &&
416
- context.mongooseCollection.conn.base &&
417
- context.mongooseCollection.conn.base.options;
428
+ const mongooseOptions = context?.mongooseCollection?.conn?.base?.options;
418
429
  if (mongooseOptions) {
419
430
  if ('strictQuery' in mongooseOptions) {
420
431
  return mongooseOptions.strictQuery;
421
432
  }
422
- if ('strict' in mongooseOptions) {
423
- return mongooseOptions.strict;
424
- }
425
433
  }
426
434
  return schemaOptions.strictQuery;
427
435
  }