@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
@@ -0,0 +1,443 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies.
5
+ */
6
+
7
+ const CastError = require('../error/cast');
8
+ const EventEmitter = require('events').EventEmitter;
9
+ const ObjectExpectedError = require('../error/objectExpected');
10
+ const SchemaSubdocumentOptions = require('../options/schemaSubdocumentOptions');
11
+ const SchemaType = require('../schemaType');
12
+ const applyDefaults = require('../helpers/document/applyDefaults');
13
+ const $exists = require('./operators/exists');
14
+ const castToNumber = require('./operators/helpers').castToNumber;
15
+ const discriminator = require('../helpers/model/discriminator');
16
+ const geospatial = require('./operators/geospatial');
17
+ const getConstructor = require('../helpers/discriminator/getConstructor');
18
+ const idGetter = require('../helpers/schema/idGetter');
19
+ const handleIdOption = require('../helpers/schema/handleIdOption');
20
+ const internalToObjectOptions = require('../options').internalToObjectOptions;
21
+ const isExclusive = require('../helpers/projection/isExclusive');
22
+ const utils = require('../utils');
23
+ const InvalidSchemaOptionError = require('../error/invalidSchemaOption');
24
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
25
+
26
+ let SubdocumentType;
27
+
28
+ module.exports = SchemaSubdocument;
29
+
30
+ /**
31
+ * Single nested subdocument SchemaType constructor.
32
+ *
33
+ * @param {Schema} schema
34
+ * @param {string} path
35
+ * @param {object} options
36
+ * @param {Schema} parentSchema
37
+ * @inherits SchemaType
38
+ * @api public
39
+ */
40
+
41
+ function SchemaSubdocument(schema, path, options, parentSchema) {
42
+ if (schema.options.timeseries) {
43
+ throw new InvalidSchemaOptionError(path, 'timeseries');
44
+ }
45
+ const schemaTypeIdOption = SchemaSubdocument.defaultOptions?._id;
46
+ if (schemaTypeIdOption != null) {
47
+ options = options || {};
48
+ options._id = schemaTypeIdOption;
49
+ }
50
+
51
+ schema = handleIdOption(schema, options);
52
+
53
+ this.Constructor = _createConstructor(schema, null, options);
54
+ this.Constructor.path = path;
55
+ this.Constructor.prototype.$basePath = path;
56
+ this.schema = schema;
57
+ this.$isSingleNested = true;
58
+ this.base = schema.base;
59
+ SchemaType.call(this, path, options, 'Embedded', parentSchema);
60
+ }
61
+
62
+ /*!
63
+ * ignore
64
+ */
65
+
66
+ SchemaSubdocument.prototype = Object.create(SchemaType.prototype);
67
+ SchemaSubdocument.prototype.constructor = SchemaSubdocument;
68
+ SchemaSubdocument.prototype.OptionsConstructor = SchemaSubdocumentOptions;
69
+
70
+ /*!
71
+ * ignore
72
+ */
73
+
74
+ function _createConstructor(schema, baseClass, options) {
75
+ // lazy load
76
+ SubdocumentType || (SubdocumentType = require('../types/subdocument'));
77
+
78
+ const _embedded = function SingleNested(value, path, parent) {
79
+ this.$__parent = parent;
80
+ SubdocumentType.apply(this, arguments);
81
+
82
+ if (parent == null) {
83
+ return;
84
+ }
85
+ this.$session(parent.$session());
86
+ };
87
+
88
+ // Must run before `$__setSchema()`, which compiles virtuals onto the prototype
89
+ schema.plugin(idGetter, { deduplicate: true });
90
+
91
+ const proto = baseClass?.prototype ?? SubdocumentType.prototype;
92
+ _embedded.prototype = Object.create(proto);
93
+ _embedded.prototype.$__setSchema(schema);
94
+ _embedded.prototype.constructor = _embedded;
95
+ _embedded.prototype.$__schemaTypeOptions = options;
96
+ _embedded.$__required = options?.required;
97
+ _embedded.base = schema.base;
98
+ _embedded.schema = schema;
99
+ _embedded.$isSingleNested = true;
100
+ _embedded.events = new EventEmitter();
101
+ _embedded.prototype.toBSON = function() {
102
+ return this.toObject(internalToObjectOptions);
103
+ };
104
+
105
+ // apply methods
106
+ for (const i in schema.methods) {
107
+ _embedded.prototype[i] = schema.methods[i];
108
+ }
109
+
110
+ // apply statics
111
+ for (const i in schema.statics) {
112
+ _embedded[i] = schema.statics[i];
113
+ }
114
+
115
+ for (const i in EventEmitter.prototype) {
116
+ _embedded[i] = EventEmitter.prototype[i];
117
+ }
118
+
119
+ return _embedded;
120
+ }
121
+
122
+ /*!
123
+ * ignore
124
+ */
125
+ const $conditionalHandlers = { ...SchemaType.prototype.$conditionalHandlers };
126
+
127
+ /**
128
+ * Special case for when users use a common location schema to represent
129
+ * locations for use with $geoWithin.
130
+ * https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
131
+ *
132
+ * @param {object} val
133
+ * @api private
134
+ */
135
+
136
+ $conditionalHandlers.$geoWithin = function handle$geoWithin(val, context) {
137
+ return { $geometry: this.castForQuery(null, val.$geometry, context) };
138
+ };
139
+
140
+ /*!
141
+ * ignore
142
+ */
143
+
144
+ $conditionalHandlers.$near =
145
+ $conditionalHandlers.$nearSphere = geospatial.cast$near;
146
+
147
+ $conditionalHandlers.$within =
148
+ $conditionalHandlers.$geoWithin = geospatial.cast$within;
149
+
150
+ $conditionalHandlers.$geoIntersects =
151
+ geospatial.cast$geoIntersects;
152
+
153
+ $conditionalHandlers.$minDistance = castToNumber;
154
+ $conditionalHandlers.$maxDistance = castToNumber;
155
+
156
+ $conditionalHandlers.$exists = $exists;
157
+
158
+ /**
159
+ * Contains the handlers for different query operators for this schema type.
160
+ * For example, `$conditionalHandlers.$exists` is the function Mongoose calls to cast `$exists` filter operators.
161
+ *
162
+ * @property $conditionalHandlers
163
+ * @memberOf SchemaSubdocument
164
+ * @instance
165
+ * @api public
166
+ */
167
+
168
+ Object.defineProperty(SchemaSubdocument.prototype, '$conditionalHandlers', {
169
+ enumerable: false,
170
+ value: $conditionalHandlers
171
+ });
172
+
173
+ /**
174
+ * Casts contents
175
+ *
176
+ * @param {object} value
177
+ * @api private
178
+ */
179
+
180
+ SchemaSubdocument.prototype.cast = function(val, doc, init, priorVal, options) {
181
+ if (val?.$isSingleNested && val.parent === doc) {
182
+ return val;
183
+ }
184
+
185
+ if (!init && val != null && (typeof val !== 'object' || Array.isArray(val))) {
186
+ throw new ObjectExpectedError(this.path, val);
187
+ }
188
+
189
+ const discriminatorKeyPath = this.schema.path(this.schema.options.discriminatorKey);
190
+ const defaultDiscriminatorValue = discriminatorKeyPath == null ? null : discriminatorKeyPath.getDefault(doc);
191
+ const Constructor = getConstructor(this.Constructor, val, defaultDiscriminatorValue);
192
+
193
+ let subdoc;
194
+
195
+ // Only pull relevant selected paths and pull out the base path
196
+ const parentSelected = doc?.$__?.selected;
197
+ const path = this.path;
198
+ const selected = parentSelected == null ? null : Object.keys(parentSelected).reduce((obj, key) => {
199
+ if (key.startsWith(path + '.')) {
200
+ obj = obj || {};
201
+ obj[key.substring(path.length + 1)] = parentSelected[key];
202
+ }
203
+ return obj;
204
+ }, null);
205
+ if (init) {
206
+ subdoc = new Constructor(void 0, selected, doc, { defaults: false });
207
+ delete subdoc.$__.defaults;
208
+ // Don't pass `path` to $init - it's only for the subdocument itself, not its fields.
209
+ // For change tracking, subdocuments use relative paths internally.
210
+ // Here, `options.path` contains the absolute path and is only used by the subdocument constructor, not by $init.
211
+ if (options.path != null) {
212
+ const { path, ...initOptions } = options;
213
+ options = initOptions;
214
+ }
215
+ subdoc.$init(val, options);
216
+ const exclude = isExclusive(selected);
217
+ applyDefaults(subdoc, selected, exclude);
218
+ } else {
219
+ options = Object.assign({}, options, { priorDoc: priorVal });
220
+ if (utils.hasOwnKeys(val) === false) {
221
+ return new Constructor({}, selected, doc, options);
222
+ }
223
+
224
+ return new Constructor(val, selected, doc, options);
225
+ }
226
+
227
+ return subdoc;
228
+ };
229
+
230
+ /**
231
+ * Casts contents for query
232
+ *
233
+ * @param {string} [$conditional] optional query operator (like `$eq` or `$in`)
234
+ * @param {any} value
235
+ * @api private
236
+ */
237
+
238
+ SchemaSubdocument.prototype.castForQuery = function($conditional, val, context, options) {
239
+ let handler;
240
+ if ($conditional != null) {
241
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
242
+ if (!handler) {
243
+ throw new Error('Can\'t use ' + $conditional);
244
+ }
245
+ return handler.call(this, val);
246
+ }
247
+ if (val == null) {
248
+ return val;
249
+ }
250
+
251
+ const Constructor = getConstructor(this.Constructor, val);
252
+ if (val instanceof Constructor) {
253
+ return val;
254
+ }
255
+
256
+ if (this.options.runSetters) {
257
+ val = this._applySetters(val, context);
258
+ }
259
+
260
+ const overrideStrict = options?.strict ?? void 0;
261
+
262
+ try {
263
+ val = new Constructor(val, overrideStrict);
264
+ } catch (error) {
265
+ // Make sure we always wrap in a CastError (gh-6803)
266
+ if (!(error instanceof CastError)) {
267
+ throw new CastError('Embedded', val, this.path, error, this);
268
+ }
269
+ throw error;
270
+ }
271
+ return val;
272
+ };
273
+
274
+ /**
275
+ * Async validation on this single nested doc.
276
+ *
277
+ * @api public
278
+ */
279
+
280
+ SchemaSubdocument.prototype.doValidate = async function doValidate(value, scope, options) {
281
+ const Constructor = getConstructor(this.Constructor, value);
282
+
283
+ if (value && !(value instanceof Constructor)) {
284
+ value = new Constructor(value, null, scope?.$__ != null ? scope : null);
285
+ }
286
+
287
+ if (options?.skipSchemaValidators) {
288
+ if (!value) {
289
+ return;
290
+ }
291
+ return value.validate();
292
+ }
293
+
294
+ await SchemaType.prototype.doValidate.call(this, value, scope, options);
295
+ if (value != null) {
296
+ await value.validate();
297
+ }
298
+ };
299
+
300
+ /**
301
+ * Synchronously validate this single nested doc
302
+ *
303
+ * @api private
304
+ */
305
+
306
+ SchemaSubdocument.prototype.doValidateSync = function(value, scope, options) {
307
+ if (!options?.skipSchemaValidators) {
308
+ const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope);
309
+ if (schemaTypeError) {
310
+ return schemaTypeError;
311
+ }
312
+ }
313
+ if (!value) {
314
+ return;
315
+ }
316
+ return value.$__validateSync();
317
+ };
318
+
319
+ /**
320
+ * Adds a discriminator to this single nested subdocument.
321
+ *
322
+ * #### Example:
323
+ *
324
+ * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
325
+ * const schema = Schema({ shape: shapeSchema });
326
+ *
327
+ * const singleNestedPath = parentSchema.path('shape');
328
+ * singleNestedPath.discriminator('Circle', Schema({ radius: Number }));
329
+ *
330
+ * @param {string} name
331
+ * @param {Schema} schema fields to add to the schema for instances of this sub-class
332
+ * @param {object|string} [options] If string, same as `options.value`.
333
+ * @param {string} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
334
+ * @param {boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
335
+ * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model
336
+ * @see discriminators https://mongoosejs.com/docs/discriminators.html
337
+ * @api public
338
+ */
339
+
340
+ SchemaSubdocument.prototype.discriminator = function(name, schema, options) {
341
+ options = options || {};
342
+ const value = utils.isPOJO(options) ? options.value : options;
343
+ const clone = typeof options.clone === 'boolean'
344
+ ? options.clone
345
+ : true;
346
+
347
+ if (schema.instanceOfSchema && clone) {
348
+ schema = schema.clone();
349
+ }
350
+
351
+ schema = discriminator(this.Constructor, name, schema, value, null, null, options.overwriteExisting);
352
+
353
+ // The discriminator key has `select: true`, so `applyPaths()` needs to walk
354
+ // the parent schema even if the parent schema is already compiled.
355
+ if (this.parentSchema != null) {
356
+ this.parentSchema._hasSelectedPaths = true;
357
+ }
358
+
359
+ this.Constructor.discriminators[name] = _createConstructor(schema, this.Constructor);
360
+
361
+ return this.Constructor.discriminators[name];
362
+ };
363
+
364
+ /*!
365
+ * ignore
366
+ */
367
+
368
+ SchemaSubdocument.defaultOptions = {};
369
+
370
+ /**
371
+ * Sets a default option for all Subdocument instances.
372
+ *
373
+ * #### Example:
374
+ *
375
+ * // Make all subdocuments required by default.
376
+ * mongoose.Schema.Types.Subdocument.set('required', true);
377
+ *
378
+ * @param {string} option The option you'd like to set the value for
379
+ * @param {any} value value for option
380
+ * @return {void}
381
+ * @function set
382
+ * @static
383
+ * @api public
384
+ */
385
+
386
+ SchemaSubdocument.set = SchemaType.set;
387
+
388
+ SchemaSubdocument.setters = [];
389
+
390
+ /**
391
+ * Attaches a getter for all Subdocument instances
392
+ *
393
+ * @param {Function} getter
394
+ * @return {this}
395
+ * @function get
396
+ * @static
397
+ * @api public
398
+ */
399
+
400
+ SchemaSubdocument.get = SchemaType.get;
401
+
402
+ /*!
403
+ * ignore
404
+ */
405
+
406
+ SchemaSubdocument.prototype.toJSON = function toJSON() {
407
+ return { path: this.path, options: this.options };
408
+ };
409
+
410
+ /*!
411
+ * ignore
412
+ */
413
+
414
+ SchemaSubdocument.prototype.clone = function() {
415
+ const schematype = new this.constructor(
416
+ this.schema,
417
+ this.path,
418
+ { ...this.options, _skipApplyDiscriminators: true },
419
+ this.parentSchema
420
+ );
421
+ schematype.validators = this.validators.slice();
422
+ if (this.requiredValidator !== undefined) {
423
+ schematype.requiredValidator = this.requiredValidator;
424
+ }
425
+ schematype.Constructor.discriminators = Object.assign({}, this.Constructor.discriminators);
426
+ schematype._appliedDiscriminators = this._appliedDiscriminators;
427
+ return schematype;
428
+ };
429
+
430
+ /**
431
+ * Returns this schema type's representation in a JSON schema.
432
+ *
433
+ * @param {object} [options]
434
+ * @param {boolean} [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
435
+ * @returns {object} JSON schema properties
436
+ */
437
+
438
+ SchemaSubdocument.prototype.toJSONSchema = function toJSONSchema(options) {
439
+ return {
440
+ ...this.schema.toJSONSchema(options),
441
+ ...this._createJSONSchemaTypeDefinition('object', 'object', options)
442
+ };
443
+ };
@@ -3,3 +3,5 @@
3
3
  exports.schemaMixedSymbol = Symbol.for('mongoose:schema_mixed');
4
4
 
5
5
  exports.builtInMiddleware = Symbol.for('mongoose:built-in-middleware');
6
+ exports.skipOnSubdocuments = Symbol('mongoose:skip-on-subdocuments');
7
+ exports.requiresShardKey = Symbol.for('mongoose:requires-shard-key');
@@ -0,0 +1,167 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * ignore
5
+ */
6
+
7
+ const SchemaUnionOptions = require('../options/schemaUnionOptions');
8
+ const SchemaType = require('../schemaType');
9
+
10
+ const firstValueSymbol = Symbol('firstValue');
11
+
12
+ /*!
13
+ * ignore
14
+ */
15
+
16
+ class Union extends SchemaType {
17
+ /**
18
+ * Create a Union schema type.
19
+ *
20
+ * @param {string} key the path in the schema for this schema type
21
+ * @param {object} options SchemaType-specific options (must have 'of' as array)
22
+ * @param {object} schemaOptions additional options from the schema this schematype belongs to
23
+ * @param {Schema} parentSchema the schema this schematype belongs to
24
+ */
25
+ constructor(key, options, schemaOptions, parentSchema) {
26
+ super(key, options, 'Union', parentSchema);
27
+ if (!Array.isArray(options?.of) || options.of.length === 0) {
28
+ throw new Error('Union schema type requires an array of types');
29
+ }
30
+ this.schemaTypes = options.of.map(obj => parentSchema.interpretAsType(key, obj, schemaOptions));
31
+ this.$isSchemaUnion = true;
32
+ }
33
+
34
+ cast(val, doc, init, prev, options) {
35
+ let firstValue = firstValueSymbol;
36
+ let lastError;
37
+ // Loop through each schema type in the union. If one of the schematypes returns a value that is `=== val`, then
38
+ // use `val`. Otherwise, if one of the schematypes casted successfully, use the first successfully casted value.
39
+ // Finally, if none of the schematypes casted successfully, throw the error from the last schema type in the union.
40
+ // The `=== val` check is a workaround to ensure that the original value is returned if it matches one of the schema types,
41
+ // avoiding cases like where numbers are casted to strings or dates even if the schema type is a number.
42
+ for (let i = 0; i < this.schemaTypes.length; ++i) {
43
+ try {
44
+ const casted = this.schemaTypes[i].cast(val, doc, init, prev, options);
45
+ if (casted === val) {
46
+ return casted;
47
+ }
48
+ if (firstValue === firstValueSymbol) {
49
+ firstValue = casted;
50
+ }
51
+ } catch (error) {
52
+ lastError = error;
53
+ }
54
+ }
55
+ if (firstValue !== firstValueSymbol) {
56
+ return firstValue;
57
+ }
58
+ throw lastError;
59
+ }
60
+
61
+ // Setters also need to be aware of casting - we need to apply the setters of the entry in the union we choose.
62
+ applySetters(val, doc, init, prev, options) {
63
+ // Setters on the union path itself run first, so they can change which entry
64
+ // in the union the value resolves to.
65
+ val = this._applySetters(val, doc, init, prev, options);
66
+
67
+ let firstValue = firstValueSymbol;
68
+ let lastError;
69
+ // Loop through each schema type in the union. If one of the schematypes returns a value that is `=== val`, then
70
+ // use `val`. Otherwise, if one of the schematypes casted successfully, use the first successfully casted value.
71
+ // Finally, if none of the schematypes casted successfully, throw the error from the last schema type in the union.
72
+ // The `=== val` check is a workaround to ensure that the original value is returned if it matches one of the schema types,
73
+ // avoiding cases like where numbers are casted to strings or dates even if the schema type is a number.
74
+ for (let i = 0; i < this.schemaTypes.length; ++i) {
75
+ try {
76
+ let castedVal = this.schemaTypes[i]._applySetters(val, doc, init, prev, options);
77
+ if (castedVal == null) {
78
+ castedVal = this.schemaTypes[i]._castNullish(castedVal);
79
+ } else {
80
+ castedVal = this.schemaTypes[i].cast(castedVal, doc, init, prev, options);
81
+ }
82
+ if (castedVal === val) {
83
+ return castedVal;
84
+ }
85
+ if (firstValue === firstValueSymbol) {
86
+ firstValue = castedVal;
87
+ }
88
+ } catch (error) {
89
+ lastError = error;
90
+ }
91
+ }
92
+ if (firstValue !== firstValueSymbol) {
93
+ return firstValue;
94
+ }
95
+ throw lastError;
96
+ }
97
+
98
+ async doValidate(value, scope, options) {
99
+ if (options && options.skipSchemaValidators) {
100
+ if (value != null && typeof value.validate === 'function') {
101
+ return value.validate();
102
+ }
103
+ return;
104
+ }
105
+
106
+ await super.doValidate(value, scope, options);
107
+ if (value != null && typeof value.validate === 'function') {
108
+ await value.validate();
109
+ }
110
+ }
111
+
112
+ doValidateSync(value, scope, options) {
113
+ if (!options || !options.skipSchemaValidators) {
114
+ const schemaTypeError = super.doValidateSync(value, scope, options);
115
+ if (schemaTypeError) {
116
+ return schemaTypeError;
117
+ }
118
+ }
119
+ if (value != null && typeof value.$__validateSync === 'function') {
120
+ return value.$__validateSync();
121
+ }
122
+ }
123
+
124
+ clone() {
125
+ const schematype = super.clone();
126
+
127
+ schematype.schemaTypes = this.schemaTypes.map(schemaType => schemaType.clone());
128
+ return schematype;
129
+ }
130
+
131
+ /**
132
+ * Returns this schema type's representation in a JSON schema.
133
+ *
134
+ * @param {object} [options]
135
+ * @param {boolean} [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
136
+ * @returns {object} JSON schema properties
137
+ */
138
+ toJSONSchema(options) {
139
+ const isRequired = this.options.required && typeof this.options.required !== 'function';
140
+ const childOptions = { ...options, _overrideRequired: true };
141
+ const jsonSchemas = this.schemaTypes.map(schemaType => schemaType.toJSONSchema(childOptions));
142
+ if (isRequired) {
143
+ return { anyOf: jsonSchemas };
144
+ }
145
+
146
+ return {
147
+ anyOf: [
148
+ options?.useBsonType ? { bsonType: 'null' } : { type: 'null' },
149
+ ...jsonSchemas
150
+ ]
151
+ };
152
+ }
153
+ }
154
+
155
+ /**
156
+ * This schema type's name, to defend against minifiers that mangle
157
+ * function names.
158
+ *
159
+ * @api public
160
+ */
161
+ Union.schemaName = 'Union';
162
+
163
+ Union.defaultOptions = {};
164
+
165
+ Union.prototype.OptionsConstructor = SchemaUnionOptions;
166
+
167
+ module.exports = Union;