@depup/mongoose 9.1.3-depup.0

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 (295) hide show
  1. package/LICENSE.md +22 -0
  2. package/README.md +397 -0
  3. package/SECURITY.md +1 -0
  4. package/eslint.config.mjs +198 -0
  5. package/index.js +64 -0
  6. package/lib/aggregate.js +1189 -0
  7. package/lib/cast/bigint.js +46 -0
  8. package/lib/cast/boolean.js +32 -0
  9. package/lib/cast/date.js +41 -0
  10. package/lib/cast/decimal128.js +39 -0
  11. package/lib/cast/double.js +50 -0
  12. package/lib/cast/int32.js +36 -0
  13. package/lib/cast/number.js +42 -0
  14. package/lib/cast/objectid.js +29 -0
  15. package/lib/cast/string.js +37 -0
  16. package/lib/cast/uuid.js +35 -0
  17. package/lib/cast.js +436 -0
  18. package/lib/collection.js +321 -0
  19. package/lib/connection.js +1855 -0
  20. package/lib/connectionState.js +26 -0
  21. package/lib/constants.js +73 -0
  22. package/lib/cursor/aggregationCursor.js +466 -0
  23. package/lib/cursor/changeStream.js +198 -0
  24. package/lib/cursor/queryCursor.js +622 -0
  25. package/lib/document.js +5521 -0
  26. package/lib/driver.js +15 -0
  27. package/lib/drivers/SPEC.md +4 -0
  28. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  29. package/lib/drivers/node-mongodb-native/collection.js +393 -0
  30. package/lib/drivers/node-mongodb-native/connection.js +506 -0
  31. package/lib/drivers/node-mongodb-native/index.js +10 -0
  32. package/lib/error/browserMissingSchema.js +29 -0
  33. package/lib/error/bulkSaveIncompleteError.js +44 -0
  34. package/lib/error/bulkWriteError.js +41 -0
  35. package/lib/error/cast.js +158 -0
  36. package/lib/error/createCollectionsError.js +26 -0
  37. package/lib/error/divergentArray.js +40 -0
  38. package/lib/error/eachAsyncMultiError.js +41 -0
  39. package/lib/error/index.js +237 -0
  40. package/lib/error/invalidSchemaOption.js +32 -0
  41. package/lib/error/messages.js +47 -0
  42. package/lib/error/missingSchema.js +33 -0
  43. package/lib/error/mongooseError.js +13 -0
  44. package/lib/error/notFound.js +47 -0
  45. package/lib/error/objectExpected.js +31 -0
  46. package/lib/error/objectParameter.js +31 -0
  47. package/lib/error/overwriteModel.js +31 -0
  48. package/lib/error/parallelSave.js +33 -0
  49. package/lib/error/parallelValidate.js +33 -0
  50. package/lib/error/serverSelection.js +62 -0
  51. package/lib/error/setOptionError.js +103 -0
  52. package/lib/error/strict.js +35 -0
  53. package/lib/error/strictPopulate.js +31 -0
  54. package/lib/error/syncIndexes.js +30 -0
  55. package/lib/error/validation.js +97 -0
  56. package/lib/error/validator.js +100 -0
  57. package/lib/error/version.js +38 -0
  58. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +39 -0
  59. package/lib/helpers/aggregate/stringifyFunctionOperators.js +50 -0
  60. package/lib/helpers/arrayDepth.js +33 -0
  61. package/lib/helpers/clone.js +204 -0
  62. package/lib/helpers/common.js +127 -0
  63. package/lib/helpers/createJSONSchemaTypeDefinition.js +24 -0
  64. package/lib/helpers/cursor/eachAsync.js +225 -0
  65. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  66. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +16 -0
  67. package/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js +12 -0
  68. package/lib/helpers/discriminator/getConstructor.js +29 -0
  69. package/lib/helpers/discriminator/getDiscriminatorByValue.js +28 -0
  70. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +27 -0
  71. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +91 -0
  72. package/lib/helpers/document/applyDefaults.js +132 -0
  73. package/lib/helpers/document/applyTimestamps.js +106 -0
  74. package/lib/helpers/document/applyVirtuals.js +147 -0
  75. package/lib/helpers/document/cleanModifiedSubpaths.js +45 -0
  76. package/lib/helpers/document/compile.js +238 -0
  77. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  78. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +53 -0
  79. package/lib/helpers/document/handleSpreadDoc.js +35 -0
  80. package/lib/helpers/each.js +25 -0
  81. package/lib/helpers/error/combinePathErrors.js +22 -0
  82. package/lib/helpers/firstKey.js +8 -0
  83. package/lib/helpers/get.js +65 -0
  84. package/lib/helpers/getConstructorName.js +16 -0
  85. package/lib/helpers/getDefaultBulkwriteResult.js +18 -0
  86. package/lib/helpers/getFunctionName.js +10 -0
  87. package/lib/helpers/immediate.js +16 -0
  88. package/lib/helpers/indexes/applySchemaCollation.js +13 -0
  89. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +14 -0
  90. package/lib/helpers/indexes/getRelatedIndexes.js +63 -0
  91. package/lib/helpers/indexes/isDefaultIdIndex.js +18 -0
  92. package/lib/helpers/indexes/isIndexEqual.js +95 -0
  93. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  94. package/lib/helpers/indexes/isTextIndex.js +16 -0
  95. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  96. package/lib/helpers/isAsyncFunction.js +9 -0
  97. package/lib/helpers/isBsonType.js +15 -0
  98. package/lib/helpers/isMongooseObject.js +22 -0
  99. package/lib/helpers/isObject.js +16 -0
  100. package/lib/helpers/isPOJO.js +12 -0
  101. package/lib/helpers/isPromise.js +6 -0
  102. package/lib/helpers/isSimpleValidator.js +22 -0
  103. package/lib/helpers/minimize.js +41 -0
  104. package/lib/helpers/model/applyDefaultsToPOJO.js +52 -0
  105. package/lib/helpers/model/applyHooks.js +140 -0
  106. package/lib/helpers/model/applyMethods.js +70 -0
  107. package/lib/helpers/model/applyStaticHooks.js +33 -0
  108. package/lib/helpers/model/applyStatics.js +13 -0
  109. package/lib/helpers/model/castBulkWrite.js +316 -0
  110. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  111. package/lib/helpers/model/discriminator.js +265 -0
  112. package/lib/helpers/model/pushNestedArrayPaths.js +15 -0
  113. package/lib/helpers/omitUndefined.js +20 -0
  114. package/lib/helpers/once.js +12 -0
  115. package/lib/helpers/parallelLimit.js +37 -0
  116. package/lib/helpers/path/parentPaths.js +18 -0
  117. package/lib/helpers/path/setDottedPath.js +33 -0
  118. package/lib/helpers/pluralize.js +95 -0
  119. package/lib/helpers/populate/assignRawDocsToIdStructure.js +129 -0
  120. package/lib/helpers/populate/assignVals.js +360 -0
  121. package/lib/helpers/populate/createPopulateQueryFilter.js +97 -0
  122. package/lib/helpers/populate/getModelsMapForPopulate.js +776 -0
  123. package/lib/helpers/populate/getSchemaTypes.js +228 -0
  124. package/lib/helpers/populate/getVirtual.js +103 -0
  125. package/lib/helpers/populate/leanPopulateMap.js +7 -0
  126. package/lib/helpers/populate/lookupLocalFields.js +40 -0
  127. package/lib/helpers/populate/markArraySubdocsPopulated.js +49 -0
  128. package/lib/helpers/populate/modelNamesFromRefPath.js +66 -0
  129. package/lib/helpers/populate/removeDeselectedForeignField.js +31 -0
  130. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  131. package/lib/helpers/populate/skipPopulateValue.js +10 -0
  132. package/lib/helpers/populate/validateRef.js +19 -0
  133. package/lib/helpers/printJestWarning.js +21 -0
  134. package/lib/helpers/processConnectionOptions.js +65 -0
  135. package/lib/helpers/projection/applyProjection.js +83 -0
  136. package/lib/helpers/projection/hasIncludedChildren.js +41 -0
  137. package/lib/helpers/projection/isDefiningProjection.js +18 -0
  138. package/lib/helpers/projection/isExclusive.js +37 -0
  139. package/lib/helpers/projection/isInclusive.js +39 -0
  140. package/lib/helpers/projection/isNestedProjection.js +8 -0
  141. package/lib/helpers/projection/isPathExcluded.js +40 -0
  142. package/lib/helpers/projection/isPathSelectedInclusive.js +28 -0
  143. package/lib/helpers/projection/isSubpath.js +14 -0
  144. package/lib/helpers/projection/parseProjection.js +33 -0
  145. package/lib/helpers/query/applyGlobalOption.js +29 -0
  146. package/lib/helpers/query/cast$expr.js +287 -0
  147. package/lib/helpers/query/castFilterPath.js +54 -0
  148. package/lib/helpers/query/castUpdate.js +643 -0
  149. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +103 -0
  150. package/lib/helpers/query/handleImmutable.js +44 -0
  151. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  152. package/lib/helpers/query/hasDollarKeys.js +23 -0
  153. package/lib/helpers/query/isOperator.js +14 -0
  154. package/lib/helpers/query/sanitizeFilter.js +38 -0
  155. package/lib/helpers/query/sanitizeProjection.js +14 -0
  156. package/lib/helpers/query/selectPopulatedFields.js +62 -0
  157. package/lib/helpers/query/trusted.js +13 -0
  158. package/lib/helpers/query/validOps.js +3 -0
  159. package/lib/helpers/schema/addAutoId.js +7 -0
  160. package/lib/helpers/schema/applyBuiltinPlugins.js +12 -0
  161. package/lib/helpers/schema/applyPlugins.js +55 -0
  162. package/lib/helpers/schema/applyReadConcern.js +20 -0
  163. package/lib/helpers/schema/applyWriteConcern.js +39 -0
  164. package/lib/helpers/schema/cleanPositionalOperators.js +12 -0
  165. package/lib/helpers/schema/getIndexes.js +171 -0
  166. package/lib/helpers/schema/getKeysInSchemaOrder.js +28 -0
  167. package/lib/helpers/schema/getPath.js +43 -0
  168. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  169. package/lib/helpers/schema/handleIdOption.js +20 -0
  170. package/lib/helpers/schema/handleTimestampOption.js +24 -0
  171. package/lib/helpers/schema/idGetter.js +34 -0
  172. package/lib/helpers/schema/merge.js +36 -0
  173. package/lib/helpers/schematype/handleImmutable.js +50 -0
  174. package/lib/helpers/setDefaultsOnInsert.js +158 -0
  175. package/lib/helpers/specialProperties.js +3 -0
  176. package/lib/helpers/symbols.js +20 -0
  177. package/lib/helpers/timers.js +3 -0
  178. package/lib/helpers/timestamps/setDocumentTimestamps.js +26 -0
  179. package/lib/helpers/timestamps/setupTimestamps.js +116 -0
  180. package/lib/helpers/topology/allServersUnknown.js +12 -0
  181. package/lib/helpers/topology/isAtlas.js +31 -0
  182. package/lib/helpers/topology/isSSLError.js +16 -0
  183. package/lib/helpers/update/applyTimestampsToChildren.js +193 -0
  184. package/lib/helpers/update/applyTimestampsToUpdate.js +131 -0
  185. package/lib/helpers/update/castArrayFilters.js +113 -0
  186. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  187. package/lib/helpers/update/modifiedPaths.js +33 -0
  188. package/lib/helpers/update/moveImmutableProperties.js +53 -0
  189. package/lib/helpers/update/removeUnusedArrayFilters.js +32 -0
  190. package/lib/helpers/update/updatedPathsByArrayFilter.js +27 -0
  191. package/lib/helpers/updateValidators.js +193 -0
  192. package/lib/index.js +17 -0
  193. package/lib/internal.js +46 -0
  194. package/lib/model.js +5010 -0
  195. package/lib/modifiedPathsSnapshot.js +9 -0
  196. package/lib/mongoose.js +1411 -0
  197. package/lib/options/populateOptions.js +36 -0
  198. package/lib/options/propertyOptions.js +8 -0
  199. package/lib/options/saveOptions.js +16 -0
  200. package/lib/options/schemaArrayOptions.js +78 -0
  201. package/lib/options/schemaBufferOptions.js +38 -0
  202. package/lib/options/schemaDateOptions.js +71 -0
  203. package/lib/options/schemaDocumentArrayOptions.js +68 -0
  204. package/lib/options/schemaMapOptions.js +43 -0
  205. package/lib/options/schemaNumberOptions.js +101 -0
  206. package/lib/options/schemaObjectIdOptions.js +64 -0
  207. package/lib/options/schemaStringOptions.js +138 -0
  208. package/lib/options/schemaSubdocumentOptions.js +66 -0
  209. package/lib/options/schemaTypeOptions.js +244 -0
  210. package/lib/options/schemaUnionOptions.js +32 -0
  211. package/lib/options/virtualOptions.js +164 -0
  212. package/lib/options.js +17 -0
  213. package/lib/plugins/index.js +6 -0
  214. package/lib/plugins/saveSubdocs.js +76 -0
  215. package/lib/plugins/sharding.js +84 -0
  216. package/lib/plugins/trackTransaction.js +84 -0
  217. package/lib/plugins/validateBeforeSave.js +41 -0
  218. package/lib/query.js +5673 -0
  219. package/lib/queryHelpers.js +387 -0
  220. package/lib/schema/array.js +699 -0
  221. package/lib/schema/bigint.js +282 -0
  222. package/lib/schema/boolean.js +332 -0
  223. package/lib/schema/buffer.js +343 -0
  224. package/lib/schema/date.js +467 -0
  225. package/lib/schema/decimal128.js +263 -0
  226. package/lib/schema/documentArray.js +656 -0
  227. package/lib/schema/documentArrayElement.js +137 -0
  228. package/lib/schema/double.js +246 -0
  229. package/lib/schema/index.js +32 -0
  230. package/lib/schema/int32.js +289 -0
  231. package/lib/schema/map.js +201 -0
  232. package/lib/schema/mixed.js +146 -0
  233. package/lib/schema/number.js +510 -0
  234. package/lib/schema/objectId.js +333 -0
  235. package/lib/schema/operators/bitwise.js +38 -0
  236. package/lib/schema/operators/exists.js +12 -0
  237. package/lib/schema/operators/geospatial.js +107 -0
  238. package/lib/schema/operators/helpers.js +32 -0
  239. package/lib/schema/operators/text.js +39 -0
  240. package/lib/schema/operators/type.js +20 -0
  241. package/lib/schema/string.js +733 -0
  242. package/lib/schema/subdocument.js +436 -0
  243. package/lib/schema/symbols.js +5 -0
  244. package/lib/schema/union.js +113 -0
  245. package/lib/schema/uuid.js +305 -0
  246. package/lib/schema.js +3226 -0
  247. package/lib/schemaType.js +1835 -0
  248. package/lib/stateMachine.js +232 -0
  249. package/lib/types/array/index.js +119 -0
  250. package/lib/types/array/isMongooseArray.js +5 -0
  251. package/lib/types/array/methods/index.js +1095 -0
  252. package/lib/types/arraySubdocument.js +207 -0
  253. package/lib/types/buffer.js +294 -0
  254. package/lib/types/decimal128.js +13 -0
  255. package/lib/types/documentArray/index.js +113 -0
  256. package/lib/types/documentArray/isMongooseDocumentArray.js +5 -0
  257. package/lib/types/documentArray/methods/index.js +415 -0
  258. package/lib/types/double.js +13 -0
  259. package/lib/types/index.js +23 -0
  260. package/lib/types/map.js +419 -0
  261. package/lib/types/objectid.js +41 -0
  262. package/lib/types/subdocument.js +464 -0
  263. package/lib/types/uuid.js +13 -0
  264. package/lib/utils.js +1054 -0
  265. package/lib/validOptions.js +42 -0
  266. package/lib/virtualType.js +204 -0
  267. package/package.json +148 -0
  268. package/types/aggregate.d.ts +180 -0
  269. package/types/augmentations.d.ts +9 -0
  270. package/types/callback.d.ts +8 -0
  271. package/types/collection.d.ts +49 -0
  272. package/types/connection.d.ts +297 -0
  273. package/types/cursor.d.ts +67 -0
  274. package/types/document.d.ts +374 -0
  275. package/types/error.d.ts +143 -0
  276. package/types/expressions.d.ts +3053 -0
  277. package/types/helpers.d.ts +32 -0
  278. package/types/index.d.ts +1056 -0
  279. package/types/indexes.d.ts +97 -0
  280. package/types/inferhydrateddoctype.d.ts +115 -0
  281. package/types/inferrawdoctype.d.ts +135 -0
  282. package/types/inferschematype.d.ts +337 -0
  283. package/types/middlewares.d.ts +59 -0
  284. package/types/models.d.ts +1306 -0
  285. package/types/mongooseoptions.d.ts +228 -0
  286. package/types/pipelinestage.d.ts +333 -0
  287. package/types/populate.d.ts +53 -0
  288. package/types/query.d.ts +934 -0
  289. package/types/schemaoptions.d.ts +282 -0
  290. package/types/schematypes.d.ts +654 -0
  291. package/types/session.d.ts +32 -0
  292. package/types/types.d.ts +109 -0
  293. package/types/utility.d.ts +175 -0
  294. package/types/validation.d.ts +39 -0
  295. package/types/virtuals.d.ts +14 -0
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ const isBsonType = require('../isBsonType');
4
+
5
+ module.exports = function areDiscriminatorValuesEqual(a, b) {
6
+ if (typeof a === 'string' && typeof b === 'string') {
7
+ return a === b;
8
+ }
9
+ if (typeof a === 'number' && typeof b === 'number') {
10
+ return a === b;
11
+ }
12
+ if (isBsonType(a, 'ObjectId') && isBsonType(b, 'ObjectId')) {
13
+ return a.toString() === b.toString();
14
+ }
15
+ return false;
16
+ };
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) {
4
+ const userProjectedInPath = Object.keys(userProjection).
5
+ reduce((cur, key) => cur || key.startsWith(path + '.'), false);
6
+ const _discriminatorKey = path + '.' + schema.options.discriminatorKey;
7
+ if (!userProjectedInPath &&
8
+ addedPaths.length === 1 &&
9
+ addedPaths[0] === _discriminatorKey) {
10
+ selected.splice(selected.indexOf(_discriminatorKey), 1);
11
+ }
12
+ };
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ const getDiscriminatorByValue = require('./getDiscriminatorByValue');
4
+
5
+ /**
6
+ * Find the correct constructor, taking into account discriminators
7
+ * @api private
8
+ */
9
+
10
+ module.exports = function getConstructor(Constructor, value, defaultDiscriminatorValue) {
11
+ const discriminatorKey = Constructor.schema.options.discriminatorKey;
12
+ let discriminatorValue = value?.[discriminatorKey];
13
+ if (discriminatorValue == null) {
14
+ discriminatorValue = defaultDiscriminatorValue;
15
+ }
16
+ if (Constructor.discriminators &&
17
+ discriminatorValue != null) {
18
+ if (Constructor.discriminators[discriminatorValue]) {
19
+ Constructor = Constructor.discriminators[discriminatorValue];
20
+ } else {
21
+ const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, discriminatorValue);
22
+ if (constructorByValue) {
23
+ Constructor = constructorByValue;
24
+ }
25
+ }
26
+ }
27
+
28
+ return Constructor;
29
+ };
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ const areDiscriminatorValuesEqual = require('./areDiscriminatorValuesEqual');
4
+
5
+ /**
6
+ * returns discriminator by discriminatorMapping.value
7
+ *
8
+ * @param {Object} discriminators
9
+ * @param {string} value
10
+ * @api private
11
+ */
12
+
13
+ module.exports = function getDiscriminatorByValue(discriminators, value) {
14
+ if (discriminators == null) {
15
+ return null;
16
+ }
17
+ for (const name of Object.keys(discriminators)) {
18
+ const it = discriminators[name];
19
+ if (
20
+ it.schema &&
21
+ it.schema.discriminatorMapping &&
22
+ areDiscriminatorValuesEqual(it.schema.discriminatorMapping.value, value)
23
+ ) {
24
+ return it;
25
+ }
26
+ }
27
+ return null;
28
+ };
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ const areDiscriminatorValuesEqual = require('./areDiscriminatorValuesEqual');
4
+
5
+ /**
6
+ * returns discriminator by discriminatorMapping.value
7
+ *
8
+ * @param {Schema} schema
9
+ * @param {string} value
10
+ * @api private
11
+ */
12
+
13
+ module.exports = function getSchemaDiscriminatorByValue(schema, value) {
14
+ if (schema?.discriminators == null) {
15
+ return null;
16
+ }
17
+ for (const key of Object.keys(schema.discriminators)) {
18
+ const discriminatorSchema = schema.discriminators[key];
19
+ if (discriminatorSchema.discriminatorMapping == null) {
20
+ continue;
21
+ }
22
+ if (areDiscriminatorValuesEqual(discriminatorSchema.discriminatorMapping.value, value)) {
23
+ return discriminatorSchema;
24
+ }
25
+ }
26
+ return null;
27
+ };
@@ -0,0 +1,91 @@
1
+ 'use strict';
2
+ const schemaMerge = require('../schema/merge');
3
+ const specialProperties = require('../../helpers/specialProperties');
4
+ const isBsonType = require('../../helpers/isBsonType');
5
+ const ObjectId = require('../../types/objectid');
6
+ const SchemaType = require('../../schemaType');
7
+ const isObject = require('../../helpers/isObject');
8
+ /**
9
+ * Merges `from` into `to` without overwriting existing properties.
10
+ *
11
+ * @param {Object} to
12
+ * @param {Object} from
13
+ * @param {String} [path]
14
+ * @api private
15
+ */
16
+
17
+ module.exports = function mergeDiscriminatorSchema(to, from, path, seen) {
18
+ const keys = Object.keys(from);
19
+ let i = 0;
20
+ const len = keys.length;
21
+ let key;
22
+
23
+ path = path || '';
24
+ seen = seen || new WeakSet();
25
+
26
+ if (seen.has(from)) {
27
+ return;
28
+ }
29
+ seen.add(from);
30
+
31
+ while (i < len) {
32
+ key = keys[i++];
33
+ if (!path) {
34
+ if (key === 'discriminators' ||
35
+ key === 'base' ||
36
+ key === '_applyDiscriminators' ||
37
+ key === '_userProvidedOptions' ||
38
+ key === 'options' ||
39
+ key === 'tree') {
40
+ continue;
41
+ }
42
+ }
43
+ if (path === 'tree' && from?.instanceOfSchema) {
44
+ continue;
45
+ }
46
+ if (specialProperties.has(key)) {
47
+ continue;
48
+ }
49
+ if (to[key] == null) {
50
+ to[key] = from[key];
51
+ } else if (isObject(from[key])) {
52
+ if (!isObject(to[key])) {
53
+ to[key] = {};
54
+ }
55
+ if (from[key] != null) {
56
+ // Skip merging schemas if we're creating a discriminator schema and
57
+ // base schema has a given path as a single nested but discriminator schema
58
+ // has the path as a document array, or vice versa (gh-9534)
59
+ if ((from[key].$isSingleNested && to[key].$isMongooseDocumentArray) ||
60
+ (from[key].$isMongooseDocumentArray && to[key].$isSingleNested) ||
61
+ (from[key].$isMongooseDocumentArrayElement && to[key].$isMongooseDocumentArrayElement)) {
62
+ continue;
63
+ } else if (from[key].instanceOfSchema) {
64
+ if (to[key].instanceOfSchema) {
65
+ schemaMerge(to[key], from[key].clone(), true);
66
+ } else {
67
+ to[key] = from[key].clone();
68
+ }
69
+ continue;
70
+ } else if (isBsonType(from[key], 'ObjectId')) {
71
+ to[key] = new ObjectId(from[key]);
72
+ continue;
73
+ } else if (from[key] instanceof SchemaType) {
74
+ if (to[key] == null) {
75
+ to[key] = from[key].clone();
76
+ }
77
+ // For container types with nested schemas, we need to continue to the
78
+ // recursive merge below to properly merge the nested schemas
79
+ if (!from[key].$isMongooseDocumentArray && !from[key].$isSingleNested) {
80
+ continue;
81
+ }
82
+ }
83
+ }
84
+ mergeDiscriminatorSchema(to[key], from[key], path ? path + '.' + key : key, seen);
85
+ }
86
+ }
87
+
88
+ if (from?.instanceOfSchema) {
89
+ to.tree = Object.assign({}, from.tree, to.tree);
90
+ }
91
+ };
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+
3
+ const isNestedProjection = require('../projection/isNestedProjection');
4
+
5
+ module.exports = function applyDefaults(doc, fields, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip, options) {
6
+ const paths = Object.keys(doc.$__schema.paths);
7
+ const plen = paths.length;
8
+ const skipParentChangeTracking = options?.skipParentChangeTracking;
9
+
10
+ for (let i = 0; i < plen; ++i) {
11
+ let def;
12
+ let curPath = '';
13
+ const p = paths[i];
14
+
15
+ if (p === '_id' && doc.$__.skipId) {
16
+ continue;
17
+ }
18
+
19
+ const type = doc.$__schema.paths[p];
20
+ const path = type.splitPath();
21
+ const len = path.length;
22
+ if (path[len - 1] === '$*') {
23
+ continue;
24
+ }
25
+ let included = false;
26
+ let doc_ = doc._doc;
27
+ for (let j = 0; j < len; ++j) {
28
+ if (doc_ == null) {
29
+ break;
30
+ }
31
+
32
+ const piece = path[j];
33
+ curPath += (!curPath.length ? '' : '.') + piece;
34
+
35
+ if (exclude === true) {
36
+ if (curPath in fields) {
37
+ break;
38
+ }
39
+ } else if (exclude === false && fields && !included) {
40
+ const hasSubpaths = type.$isSingleNested || type.$isMongooseDocumentArray;
41
+ if ((curPath in fields && !isNestedProjection(fields[curPath])) || (j === len - 1 && hasSubpaths && hasIncludedChildren != null && hasIncludedChildren[curPath])) {
42
+ included = true;
43
+ } else if (hasIncludedChildren != null && !hasIncludedChildren[curPath]) {
44
+ break;
45
+ }
46
+ }
47
+
48
+ if (j === len - 1) {
49
+ if (doc_[piece] !== void 0) {
50
+ break;
51
+ }
52
+
53
+ if (isBeforeSetters != null) {
54
+ if (typeof type.defaultValue === 'function') {
55
+ if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) {
56
+ break;
57
+ }
58
+ if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) {
59
+ break;
60
+ }
61
+ } else if (!isBeforeSetters) {
62
+ // Non-function defaults should always run **before** setters
63
+ continue;
64
+ }
65
+ }
66
+
67
+ if (pathsToSkip && pathsToSkip[curPath]) {
68
+ break;
69
+ }
70
+
71
+ if (fields && exclude !== null) {
72
+ if (exclude === true) {
73
+ // apply defaults to all non-excluded fields
74
+ if (p in fields) {
75
+ continue;
76
+ }
77
+
78
+ try {
79
+ def = type.getDefault(doc, false);
80
+ } catch (err) {
81
+ doc.invalidate(p, err);
82
+ break;
83
+ }
84
+
85
+ if (typeof def !== 'undefined') {
86
+ doc_[piece] = def;
87
+ applyChangeTracking(doc, p, skipParentChangeTracking);
88
+ }
89
+ } else if (included) {
90
+ // selected field
91
+ try {
92
+ def = type.getDefault(doc, false);
93
+ } catch (err) {
94
+ doc.invalidate(p, err);
95
+ break;
96
+ }
97
+
98
+ if (typeof def !== 'undefined') {
99
+ doc_[piece] = def;
100
+ applyChangeTracking(doc, p, skipParentChangeTracking);
101
+ }
102
+ }
103
+ } else {
104
+ try {
105
+ def = type.getDefault(doc, false);
106
+ } catch (err) {
107
+ doc.invalidate(p, err);
108
+ break;
109
+ }
110
+
111
+ if (typeof def !== 'undefined') {
112
+ doc_[piece] = def;
113
+ applyChangeTracking(doc, p, skipParentChangeTracking);
114
+ }
115
+ }
116
+ } else {
117
+ doc_ = doc_[piece];
118
+ }
119
+ }
120
+ }
121
+ };
122
+
123
+ /*!
124
+ * ignore
125
+ */
126
+
127
+ function applyChangeTracking(doc, fullPath, skipParentChangeTracking) {
128
+ doc.$__.activePaths.default(fullPath);
129
+ if (!skipParentChangeTracking && doc.$isSubdocument && doc.$isSingleNested && doc.$parent() != null) {
130
+ doc.$parent().$__.activePaths.default(doc.$__pathRelativeToParent(fullPath));
131
+ }
132
+ }
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ const handleTimestampOption = require('../schema/handleTimestampOption');
4
+ const mpath = require('mpath');
5
+ const utils = require('../../utils');
6
+
7
+ module.exports = applyTimestamps;
8
+
9
+ /**
10
+ * Apply a given schema's timestamps to the given POJO
11
+ *
12
+ * @param {Schema} schema
13
+ * @param {Object} obj
14
+ * @param {Object} [options]
15
+ * @param {Boolean} [options.isUpdate=false] if true, treat this as an update: just set updatedAt, skip setting createdAt. If false, set both createdAt and updatedAt
16
+ * @param {Function} [options.currentTime] if set, Mongoose will call this function to get the current time.
17
+ */
18
+
19
+ function applyTimestamps(schema, obj, options) {
20
+ if (obj == null) {
21
+ return obj;
22
+ }
23
+
24
+ applyTimestampsToChildren(schema, obj, options);
25
+ return applyTimestampsToDoc(schema, obj, options);
26
+ }
27
+
28
+ /**
29
+ * Apply timestamps to any subdocuments
30
+ *
31
+ * @param {Schema} schema subdocument schema
32
+ * @param {Object} res subdocument
33
+ * @param {Object} [options]
34
+ * @param {Boolean} [options.isUpdate=false] if true, treat this as an update: just set updatedAt, skip setting createdAt. If false, set both createdAt and updatedAt
35
+ * @param {Function} [options.currentTime] if set, Mongoose will call this function to get the current time.
36
+ */
37
+
38
+ function applyTimestampsToChildren(schema, res, options) {
39
+ for (const childSchema of schema.childSchemas) {
40
+ const _path = childSchema.model.path;
41
+ const _schema = childSchema.schema;
42
+ if (!_path) {
43
+ continue;
44
+ }
45
+ const _obj = mpath.get(_path, res);
46
+ if (_obj == null || (Array.isArray(_obj) && _obj.flat(Infinity).length === 0)) {
47
+ continue;
48
+ }
49
+
50
+ applyTimestamps(_schema, _obj, options);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Apply timestamps to a given document. Does not apply timestamps to subdocuments: use `applyTimestampsToChildren` instead
56
+ *
57
+ * @param {Schema} schema
58
+ * @param {Object} obj
59
+ * @param {Object} [options]
60
+ * @param {Boolean} [options.isUpdate=false] if true, treat this as an update: just set updatedAt, skip setting createdAt. If false, set both createdAt and updatedAt
61
+ * @param {Function} [options.currentTime] if set, Mongoose will call this function to get the current time.
62
+ */
63
+
64
+ function applyTimestampsToDoc(schema, obj, options) {
65
+ if (obj == null || typeof obj !== 'object') {
66
+ return;
67
+ }
68
+ if (Array.isArray(obj)) {
69
+ for (const el of obj) {
70
+ applyTimestampsToDoc(schema, el, options);
71
+ }
72
+ return;
73
+ }
74
+
75
+ if (schema.discriminators && utils.hasOwnKeys(schema.discriminators)) {
76
+ for (const discriminatorKey of Object.keys(schema.discriminators)) {
77
+ const discriminator = schema.discriminators[discriminatorKey];
78
+ const key = discriminator.discriminatorMapping.key;
79
+ const value = discriminator.discriminatorMapping.value;
80
+ if (obj[key] == value) {
81
+ schema = discriminator;
82
+ break;
83
+ }
84
+ }
85
+ }
86
+
87
+ const createdAt = handleTimestampOption(schema.options.timestamps, 'createdAt');
88
+ const updatedAt = handleTimestampOption(schema.options.timestamps, 'updatedAt');
89
+ const currentTime = options?.currentTime;
90
+
91
+ let ts = null;
92
+ if (currentTime != null) {
93
+ ts = currentTime();
94
+ } else if (schema.base?.now) {
95
+ ts = schema.base.now();
96
+ } else {
97
+ ts = new Date();
98
+ }
99
+
100
+ if (createdAt && obj[createdAt] == null && !options?.isUpdate) {
101
+ obj[createdAt] = ts;
102
+ }
103
+ if (updatedAt) {
104
+ obj[updatedAt] = ts;
105
+ }
106
+ }
@@ -0,0 +1,147 @@
1
+ 'use strict';
2
+
3
+ const mpath = require('mpath');
4
+ const utils = require('../../utils');
5
+
6
+ module.exports = applyVirtuals;
7
+
8
+ /**
9
+ * Apply a given schema's virtuals to a given POJO
10
+ *
11
+ * @param {Schema} schema
12
+ * @param {Object} obj
13
+ * @param {Array<string>} [virtuals] optional whitelist of virtuals to apply
14
+ * @returns
15
+ */
16
+
17
+ function applyVirtuals(schema, obj, virtuals) {
18
+ if (obj == null) {
19
+ return obj;
20
+ }
21
+
22
+ let virtualsForChildren = virtuals;
23
+ let toApply = null;
24
+
25
+ if (Array.isArray(virtuals)) {
26
+ virtualsForChildren = [];
27
+ toApply = [];
28
+ for (const virtual of virtuals) {
29
+ if (virtual.length === 1) {
30
+ toApply.push(virtual[0]);
31
+ } else {
32
+ virtualsForChildren.push(virtual);
33
+ }
34
+ }
35
+ }
36
+
37
+ applyVirtualsToChildren(schema, obj, virtualsForChildren);
38
+ return applyVirtualsToDoc(schema, obj, toApply);
39
+ }
40
+
41
+ /**
42
+ * Apply virtuals to any subdocuments
43
+ *
44
+ * @param {Schema} schema subdocument schema
45
+ * @param {Object} res subdocument
46
+ * @param {Array<String>} [virtuals] optional whitelist of virtuals to apply
47
+ */
48
+
49
+ function applyVirtualsToChildren(schema, res, virtuals) {
50
+ let attachedVirtuals = false;
51
+ for (const childSchema of schema.childSchemas) {
52
+ const _path = childSchema.model.path;
53
+ const _schema = childSchema.schema;
54
+ if (!_path) {
55
+ continue;
56
+ }
57
+ const _obj = mpath.get(_path, res);
58
+ if (_obj == null || (Array.isArray(_obj) && _obj.flat(Infinity).length === 0)) {
59
+ continue;
60
+ }
61
+
62
+ let virtualsForChild = null;
63
+ if (Array.isArray(virtuals)) {
64
+ virtualsForChild = [];
65
+ for (const virtual of virtuals) {
66
+ if (virtual[0] == _path) {
67
+ virtualsForChild.push(virtual.slice(1));
68
+ }
69
+ }
70
+
71
+ if (virtualsForChild.length === 0) {
72
+ continue;
73
+ }
74
+ }
75
+
76
+ applyVirtuals(_schema, _obj, virtualsForChild);
77
+ attachedVirtuals = true;
78
+ }
79
+
80
+ if (virtuals?.length && !attachedVirtuals) {
81
+ applyVirtualsToDoc(schema, res, virtuals);
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Apply virtuals to a given document. Does not apply virtuals to subdocuments: use `applyVirtualsToChildren` instead
87
+ *
88
+ * @param {Schema} schema
89
+ * @param {Object} doc
90
+ * @param {Array<String>} [virtuals] optional whitelist of virtuals to apply
91
+ * @returns
92
+ */
93
+
94
+ function applyVirtualsToDoc(schema, obj, virtuals) {
95
+ if (obj == null || typeof obj !== 'object') {
96
+ return;
97
+ }
98
+ if (Array.isArray(obj)) {
99
+ for (const el of obj) {
100
+ applyVirtualsToDoc(schema, el, virtuals);
101
+ }
102
+ return;
103
+ }
104
+
105
+ if (schema.discriminators && utils.hasOwnKeys(schema.discriminators)) {
106
+ for (const discriminatorKey of Object.keys(schema.discriminators)) {
107
+ const discriminator = schema.discriminators[discriminatorKey];
108
+ const key = discriminator.discriminatorMapping.key;
109
+ const value = discriminator.discriminatorMapping.value;
110
+ if (obj[key] == value) {
111
+ schema = discriminator;
112
+ break;
113
+ }
114
+ }
115
+ }
116
+
117
+ if (virtuals == null) {
118
+ virtuals = Object.keys(schema.virtuals);
119
+ }
120
+ for (const virtual of virtuals) {
121
+ if (schema.virtuals[virtual] == null) {
122
+ continue;
123
+ }
124
+ const virtualType = schema.virtuals[virtual];
125
+ const sp = Array.isArray(virtual)
126
+ ? virtual
127
+ : virtual.indexOf('.') === -1
128
+ ? [virtual]
129
+ : virtual.split('.');
130
+ let cur = obj;
131
+ for (let i = 0; i < sp.length - 1; ++i) {
132
+ cur[sp[i]] = sp[i] in cur ? cur[sp[i]] : {};
133
+ cur = cur[sp[i]];
134
+ }
135
+ let val = virtualType.applyGetters(cur[sp[sp.length - 1]], obj);
136
+ const isPopulateVirtual =
137
+ virtualType.options?.ref || virtualType.options?.refPath;
138
+ if (isPopulateVirtual && val === undefined) {
139
+ if (virtualType.options.justOne) {
140
+ val = null;
141
+ } else {
142
+ val = [];
143
+ }
144
+ }
145
+ cur[sp[sp.length - 1]] = val;
146
+ }
147
+ }
@@ -0,0 +1,45 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * ignore
5
+ */
6
+
7
+ module.exports = function cleanModifiedSubpaths(doc, path, options) {
8
+ options = options || {};
9
+ const skipDocArrays = options.skipDocArrays;
10
+
11
+ let deleted = 0;
12
+ if (!doc) {
13
+ return deleted;
14
+ }
15
+
16
+ for (const modifiedPath of Object.keys(doc.$__.activePaths.getStatePaths('modify'))) {
17
+ if (skipDocArrays) {
18
+ const schemaType = doc.$__schema.path(modifiedPath);
19
+ if (schemaType?.$isMongooseDocumentArray) {
20
+ continue;
21
+ }
22
+ }
23
+ if (modifiedPath.startsWith(path + '.')) {
24
+ doc.$__.activePaths.clearPath(modifiedPath);
25
+ ++deleted;
26
+
27
+ if (doc.$isSubdocument) {
28
+ cleanParent(doc, modifiedPath);
29
+ }
30
+ }
31
+ }
32
+ return deleted;
33
+ };
34
+
35
+ function cleanParent(doc, path, seen = new Set()) {
36
+ if (seen.has(doc)) {
37
+ throw new Error('Infinite subdocument loop: subdoc with _id ' + doc._id + ' is a parent of itself');
38
+ }
39
+ const parent = doc.$parent();
40
+ const newPath = doc.$__pathRelativeToParent(void 0, false) + '.' + path;
41
+ parent.$__.activePaths.clearPath(newPath);
42
+ if (parent.$isSubdocument) {
43
+ cleanParent(parent, newPath, seen);
44
+ }
45
+ }