@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,228 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * ignore
5
+ */
6
+
7
+ const Mixed = require('../../schema/mixed');
8
+ const get = require('../get');
9
+ const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
10
+ const leanPopulateMap = require('./leanPopulateMap');
11
+ const mpath = require('mpath');
12
+
13
+ const populateModelSymbol = require('../symbols').populateModelSymbol;
14
+
15
+ /**
16
+ * Given a model and its schema, find all possible schema types for `path`,
17
+ * including searching through discriminators. If `doc` is specified, will
18
+ * use the doc's values for discriminator keys when searching, otherwise
19
+ * will search all discriminators.
20
+ *
21
+ * @param {Model} model
22
+ * @param {Schema} schema
23
+ * @param {Object} doc POJO
24
+ * @param {string} path
25
+ * @api private
26
+ */
27
+
28
+ module.exports = function getSchemaTypes(model, schema, doc, path) {
29
+ const pathschema = schema.path(path);
30
+ const topLevelDoc = doc;
31
+ if (pathschema) {
32
+ return pathschema;
33
+ }
34
+
35
+ const discriminatorKey = schema.discriminatorMapping?.key;
36
+ if (discriminatorKey && model != null) {
37
+ if (doc?.[discriminatorKey] != null) {
38
+ const discriminator = getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]);
39
+ schema = discriminator?.schema || schema;
40
+ } else if (model.discriminators != null) {
41
+ return Object.keys(model.discriminators).reduce((arr, name) => {
42
+ const disc = model.discriminators[name];
43
+ return arr.concat(getSchemaTypes(disc, disc.schema, null, path));
44
+ }, []);
45
+ }
46
+ }
47
+
48
+ function search(parts, schema, subdoc, nestedPath) {
49
+ let p = parts.length + 1;
50
+ let foundschema;
51
+ let trypath;
52
+
53
+ while (p--) {
54
+ trypath = parts.slice(0, p).join('.');
55
+ foundschema = schema.path(trypath);
56
+ if (foundschema == null) {
57
+ continue;
58
+ }
59
+
60
+ if (foundschema.embeddedSchemaType || foundschema.schema) {
61
+ // array of Mixed?
62
+ if (foundschema.embeddedSchemaType instanceof Mixed) {
63
+ return foundschema.embeddedSchemaType;
64
+ }
65
+
66
+ let schemas = null;
67
+ if (foundschema.schema?.discriminators != null) {
68
+ const discriminators = foundschema.schema.discriminators;
69
+ const discriminatorKeyPath = trypath + '.' +
70
+ foundschema.schema.options.discriminatorKey;
71
+ const keys = subdoc ? mpath.get(discriminatorKeyPath, subdoc) || [] : [];
72
+ schemas = Object.keys(discriminators).
73
+ reduce(function(cur, discriminator) {
74
+ const tiedValue = discriminators[discriminator].discriminatorMapping.value;
75
+ if (doc == null || keys.indexOf(discriminator) !== -1 || keys.indexOf(tiedValue) !== -1) {
76
+ cur.push(discriminators[discriminator]);
77
+ }
78
+ return cur;
79
+ }, []);
80
+ }
81
+
82
+ // Now that we found the array, we need to check if there
83
+ // are remaining document paths to look up for casting.
84
+ // Also we need to handle array.$.path since schema.path
85
+ // doesn't work for that.
86
+ // If there is no foundschema.schema we are dealing with
87
+ // a path like array.$
88
+ if (p !== parts.length && foundschema.schema) {
89
+ let ret;
90
+ if (parts[p] === '$') {
91
+ if (p + 1 === parts.length) {
92
+ // comments.$
93
+ return foundschema;
94
+ }
95
+ // comments.$.comments.$.title
96
+ ret = search(
97
+ parts.slice(p + 1),
98
+ schema,
99
+ subdoc ? mpath.get(trypath, subdoc) : null,
100
+ nestedPath.concat(parts.slice(0, p))
101
+ );
102
+ if (ret) {
103
+ ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
104
+ (foundschema.schema.$isSingleNested ? null : foundschema);
105
+ }
106
+ return ret;
107
+ }
108
+
109
+ if (schemas != null && schemas.length > 0) {
110
+ ret = [];
111
+ for (const schema of schemas) {
112
+ const _ret = search(
113
+ parts.slice(p),
114
+ schema,
115
+ subdoc ? mpath.get(trypath, subdoc) : null,
116
+ nestedPath.concat(parts.slice(0, p))
117
+ );
118
+ if (_ret != null) {
119
+ _ret.$parentSchemaDocArray = _ret.$parentSchemaDocArray ||
120
+ (foundschema.schema.$isSingleNested ? null : foundschema);
121
+ if (_ret.$parentSchemaDocArray) {
122
+ ret.$parentSchemaDocArray = _ret.$parentSchemaDocArray;
123
+ }
124
+ ret.push(_ret);
125
+ }
126
+ }
127
+ return ret;
128
+ } else {
129
+ ret = search(
130
+ parts.slice(p),
131
+ foundschema.schema,
132
+ subdoc ? mpath.get(trypath, subdoc) : null,
133
+ nestedPath.concat(parts.slice(0, p))
134
+ );
135
+
136
+ if (ret) {
137
+ ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
138
+ (foundschema.schema.$isSingleNested ? null : foundschema);
139
+ }
140
+ return ret;
141
+ }
142
+ } else if (p !== parts.length &&
143
+ foundschema.$isMongooseArray &&
144
+ foundschema.embeddedSchemaType.$isMongooseArray) {
145
+ // Nested arrays. Drill down to the bottom of the nested array.
146
+ let type = foundschema;
147
+ while (type.$isMongooseArray && !type.$isMongooseDocumentArray) {
148
+ type = type.embeddedSchemaType;
149
+ }
150
+
151
+ const ret = search(
152
+ parts.slice(p),
153
+ type.schema,
154
+ null,
155
+ nestedPath.concat(parts.slice(0, p))
156
+ );
157
+ if (ret != null) {
158
+ return ret;
159
+ }
160
+
161
+ if (type.schema.discriminators) {
162
+ const discriminatorPaths = [];
163
+ for (const discriminatorName of Object.keys(type.schema.discriminators)) {
164
+ const _schema = type.schema.discriminators[discriminatorName] || type.schema;
165
+ const ret = search(parts.slice(p), _schema, null, nestedPath.concat(parts.slice(0, p)));
166
+ if (ret != null) {
167
+ discriminatorPaths.push(ret);
168
+ }
169
+ }
170
+ if (discriminatorPaths.length > 0) {
171
+ return discriminatorPaths;
172
+ }
173
+ }
174
+ }
175
+ } else if (foundschema.$isSchemaMap && foundschema.$__schemaType instanceof Mixed) {
176
+ return foundschema.$__schemaType;
177
+ }
178
+
179
+ const fullPath = nestedPath.concat([trypath]).join('.');
180
+ if (topLevelDoc?.$__ && topLevelDoc.$populated(fullPath, true) && p < parts.length) {
181
+ const model = topLevelDoc.$populated(fullPath, true).options[populateModelSymbol];
182
+ if (model != null) {
183
+ const ret = search(
184
+ parts.slice(p),
185
+ model.schema,
186
+ subdoc ? mpath.get(trypath, subdoc) : null,
187
+ nestedPath.concat(parts.slice(0, p))
188
+ );
189
+
190
+ return ret;
191
+ }
192
+ }
193
+
194
+ const _val = get(topLevelDoc, trypath);
195
+ if (_val != null) {
196
+ const model = Array.isArray(_val) && _val.length > 0 ?
197
+ leanPopulateMap.get(_val[0]) :
198
+ leanPopulateMap.get(_val);
199
+ // Populated using lean, `leanPopulateMap` value is the foreign model
200
+ const schema = model?.schema ?? null;
201
+ if (schema != null) {
202
+ const ret = search(
203
+ parts.slice(p),
204
+ schema,
205
+ subdoc ? mpath.get(trypath, subdoc) : null,
206
+ nestedPath.concat(parts.slice(0, p))
207
+ );
208
+
209
+ if (ret != null) {
210
+ ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
211
+ (schema.$isSingleNested ? null : schema);
212
+ return ret;
213
+ }
214
+ }
215
+ }
216
+ return foundschema;
217
+ }
218
+ }
219
+ // look for arrays
220
+ const parts = path.split('.');
221
+ for (let i = 0; i < parts.length; ++i) {
222
+ if (parts[i] === '$') {
223
+ // Re: gh-5628, because `schema.path()` doesn't take $ into account.
224
+ parts[i] = '0';
225
+ }
226
+ }
227
+ return search(parts, schema, doc, []);
228
+ };
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+
3
+ module.exports = getVirtual;
4
+
5
+ /*!
6
+ * ignore
7
+ */
8
+
9
+ function getVirtual(schema, name) {
10
+ if (schema.virtuals[name]) {
11
+ return { virtual: schema.virtuals[name], path: void 0 };
12
+ }
13
+
14
+ const parts = name.split('.');
15
+ let cur = '';
16
+ let nestedSchemaPath = '';
17
+ for (let i = 0; i < parts.length; ++i) {
18
+ cur += (cur.length > 0 ? '.' : '') + parts[i];
19
+ if (schema.virtuals[cur]) {
20
+ if (i === parts.length - 1) {
21
+ return { virtual: schema.virtuals[cur], path: nestedSchemaPath };
22
+ }
23
+ continue;
24
+ }
25
+
26
+ if (schema.nested[cur]) {
27
+ continue;
28
+ }
29
+
30
+ if (schema.paths[cur] && schema.paths[cur].schema) {
31
+ schema = schema.paths[cur].schema;
32
+ const rest = parts.slice(i + 1).join('.');
33
+
34
+ if (schema.virtuals[rest]) {
35
+ if (i === parts.length - 2) {
36
+ return {
37
+ virtual: schema.virtuals[rest],
38
+ nestedSchemaPath: [nestedSchemaPath, cur].filter(v => !!v).join('.')
39
+ };
40
+ }
41
+ continue;
42
+ }
43
+
44
+ if (i + 1 < parts.length && schema.discriminators) {
45
+ for (const key of Object.keys(schema.discriminators)) {
46
+ const res = getVirtual(schema.discriminators[key], rest);
47
+ if (res != null) {
48
+ const _path = [nestedSchemaPath, cur, res.nestedSchemaPath].
49
+ filter(v => !!v).join('.');
50
+ return {
51
+ virtual: res.virtual,
52
+ nestedSchemaPath: _path
53
+ };
54
+ }
55
+ }
56
+ }
57
+
58
+ nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur;
59
+ cur = '';
60
+ continue;
61
+ } else if (schema.paths[cur]?.$isSchemaMap && schema.paths[cur].$__schemaType?.schema) {
62
+ schema = schema.paths[cur].$__schemaType.schema;
63
+ ++i;
64
+ const rest = parts.slice(i + 1).join('.');
65
+
66
+ if (schema.virtuals[rest]) {
67
+ if (i === parts.length - 2) {
68
+ return {
69
+ virtual: schema.virtuals[rest],
70
+ nestedSchemaPath: [nestedSchemaPath, cur, '$*'].filter(v => !!v).join('.')
71
+ };
72
+ }
73
+ continue;
74
+ }
75
+
76
+ if (i + 1 < parts.length && schema.discriminators) {
77
+ for (const key of Object.keys(schema.discriminators)) {
78
+ const res = getVirtual(schema.discriminators[key], rest);
79
+ if (res != null) {
80
+ const _path = [nestedSchemaPath, cur, res.nestedSchemaPath, '$*'].
81
+ filter(v => !!v).join('.');
82
+ return {
83
+ virtual: res.virtual,
84
+ nestedSchemaPath: _path
85
+ };
86
+ }
87
+ }
88
+ }
89
+
90
+ nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + '$*' + cur;
91
+ cur = '';
92
+ }
93
+
94
+ if (schema.discriminators) {
95
+ for (const discriminatorKey of Object.keys(schema.discriminators)) {
96
+ const virtualFromDiscriminator = getVirtual(schema.discriminators[discriminatorKey], name);
97
+ if (virtualFromDiscriminator) return virtualFromDiscriminator;
98
+ }
99
+ }
100
+
101
+ return null;
102
+ }
103
+ }
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * ignore
5
+ */
6
+
7
+ module.exports = new WeakMap();
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ module.exports = function lookupLocalFields(cur, path, val) {
4
+ if (cur == null) {
5
+ return cur;
6
+ }
7
+
8
+ if (cur._doc != null) {
9
+ cur = cur._doc;
10
+ }
11
+
12
+ if (arguments.length >= 3) {
13
+ if (typeof cur !== 'object') {
14
+ return void 0;
15
+ }
16
+ if (val === void 0) {
17
+ return void 0;
18
+ }
19
+ if (cur instanceof Map) {
20
+ cur.set(path, val);
21
+ } else {
22
+ cur[path] = val;
23
+ }
24
+ return val;
25
+ }
26
+
27
+
28
+ // Support populating paths under maps using `map.$*.subpath`
29
+ if (path === '$*') {
30
+ return cur instanceof Map ?
31
+ Array.from(cur.values()) :
32
+ Object.keys(cur).map(key => cur[key]);
33
+ }
34
+
35
+ if (cur instanceof Map) {
36
+ return cur.get(path);
37
+ }
38
+
39
+ return cur[path];
40
+ };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ const utils = require('../../utils');
4
+
5
+ /**
6
+ * If populating a path within a document array, make sure each
7
+ * subdoc within the array knows its subpaths are populated.
8
+ *
9
+ * #### Example:
10
+ *
11
+ * const doc = await Article.findOne().populate('comments.author');
12
+ * doc.comments[0].populated('author'); // Should be set
13
+ *
14
+ * @param {Document} doc
15
+ * @param {Object} [populated]
16
+ * @api private
17
+ */
18
+
19
+ module.exports = function markArraySubdocsPopulated(doc, populated) {
20
+ if (doc._doc._id == null || populated == null || populated.length === 0) {
21
+ return;
22
+ }
23
+
24
+ const id = String(doc._doc._id);
25
+ for (const item of populated) {
26
+ if (item.isVirtual) {
27
+ continue;
28
+ }
29
+ const path = item.path;
30
+ const pieces = path.split('.');
31
+ for (let i = 0; i < pieces.length - 1; ++i) {
32
+ const subpath = pieces.slice(0, i + 1).join('.');
33
+ const rest = pieces.slice(i + 1).join('.');
34
+ const val = doc.get(subpath);
35
+ if (val == null) {
36
+ continue;
37
+ }
38
+
39
+ if (utils.isMongooseDocumentArray(val)) {
40
+ for (let j = 0; j < val.length; ++j) {
41
+ if (val[j]) {
42
+ val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item);
43
+ }
44
+ }
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ };
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ const MongooseError = require('../../error/mongooseError');
4
+ const isPathExcluded = require('../projection/isPathExcluded');
5
+ const lookupLocalFields = require('./lookupLocalFields');
6
+ const mpath = require('mpath');
7
+ const util = require('util');
8
+ const utils = require('../../utils');
9
+
10
+ const hasNumericPropRE = /(\.\d+$|\.\d+\.)/g;
11
+
12
+ module.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, modelSchema, queryProjection) {
13
+ if (refPath == null) {
14
+ return [];
15
+ }
16
+
17
+ if (typeof refPath === 'string' && queryProjection != null && isPathExcluded(queryProjection, refPath)) {
18
+ throw new MongooseError('refPath `' + refPath + '` must not be excluded in projection, got ' +
19
+ util.inspect(queryProjection));
20
+ }
21
+
22
+ // If populated path has numerics, the end `refPath` should too. For example,
23
+ // if populating `a.0.b` instead of `a.b` and `b` has `refPath = a.c`, we
24
+ // should return `a.0.c` for the refPath.
25
+
26
+ if (hasNumericPropRE.test(populatedPath)) {
27
+ const chunks = populatedPath.split(hasNumericPropRE);
28
+
29
+ if (chunks[chunks.length - 1] === '') {
30
+ throw new Error('Can\'t populate individual element in an array');
31
+ }
32
+
33
+ let _refPath = '';
34
+ let _remaining = refPath;
35
+ // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]`
36
+ for (let i = 0; i < chunks.length; i += 2) {
37
+ const chunk = chunks[i];
38
+ if (_remaining.startsWith(chunk + '.')) {
39
+ _refPath += _remaining.substring(0, chunk.length) + chunks[i + 1];
40
+ _remaining = _remaining.substring(chunk.length + 1);
41
+ } else if (i === chunks.length - 1) {
42
+ _refPath += _remaining;
43
+ _remaining = '';
44
+ break;
45
+ } else {
46
+ throw new Error('Could not normalize ref path, chunk ' + chunk + ' not in populated path');
47
+ }
48
+ }
49
+
50
+ const refValue = mpath.get(_refPath, doc, lookupLocalFields);
51
+ let modelNames = Array.isArray(refValue) ? refValue : [refValue];
52
+ modelNames = utils.array.flatten(modelNames);
53
+ return modelNames;
54
+ }
55
+
56
+ const refValue = mpath.get(refPath, doc, lookupLocalFields);
57
+
58
+ let modelNames;
59
+ if (modelSchema != null && Object.hasOwn(modelSchema.virtuals, refPath)) {
60
+ modelNames = [modelSchema.virtuals[refPath].applyGetters(void 0, doc)];
61
+ } else {
62
+ modelNames = Array.isArray(refValue) ? refValue : [refValue];
63
+ }
64
+
65
+ return modelNames;
66
+ };
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ const get = require('../get');
4
+ const mpath = require('mpath');
5
+ const parseProjection = require('../projection/parseProjection');
6
+
7
+ /*!
8
+ * ignore
9
+ */
10
+
11
+ module.exports = function removeDeselectedForeignField(foreignFields, options, docs) {
12
+ const projection = parseProjection(get(options, 'select', null), true) ||
13
+ parseProjection(get(options, 'options.select', null), true);
14
+
15
+ if (projection == null) {
16
+ return;
17
+ }
18
+ for (const foreignField of foreignFields) {
19
+ if (!Object.hasOwn(projection, '-' + foreignField)) {
20
+ continue;
21
+ }
22
+
23
+ for (const val of docs) {
24
+ if (val.$__ != null) {
25
+ mpath.unset(foreignField, val._doc);
26
+ } else {
27
+ mpath.unset(foreignField, val);
28
+ }
29
+ }
30
+ }
31
+ };
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Set a populated virtual value on a document's `$$populatedVirtuals` value
5
+ *
6
+ * @param {*} populatedVirtuals A document's `$$populatedVirtuals`
7
+ * @param {*} name The virtual name
8
+ * @param {*} v The result of the populate query
9
+ * @param {*} options The populate options. This function handles `justOne` and `count` options.
10
+ * @returns {Array<Document>|Document|Object|Array<Object>} the populated virtual value that was set
11
+ */
12
+
13
+ module.exports = function setPopulatedVirtualValue(populatedVirtuals, name, v, options) {
14
+ if (options.justOne || options.count) {
15
+ populatedVirtuals[name] = Array.isArray(v) ?
16
+ v[0] :
17
+ v;
18
+
19
+ if (typeof populatedVirtuals[name] !== 'object') {
20
+ populatedVirtuals[name] = options.count ? v : null;
21
+ }
22
+ } else {
23
+ populatedVirtuals[name] = Array.isArray(v) ?
24
+ v :
25
+ v == null ? [] : [v];
26
+
27
+ populatedVirtuals[name] = populatedVirtuals[name].filter(function(doc) {
28
+ return doc && typeof doc === 'object';
29
+ });
30
+ }
31
+
32
+ return populatedVirtuals[name];
33
+ };
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ module.exports = function SkipPopulateValue(val) {
4
+ if (!(this instanceof SkipPopulateValue)) {
5
+ return new SkipPopulateValue(val);
6
+ }
7
+
8
+ this.val = val;
9
+ return this;
10
+ };
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+
3
+ const MongooseError = require('../../error/mongooseError');
4
+ const util = require('util');
5
+
6
+ module.exports = validateRef;
7
+
8
+ function validateRef(ref, path) {
9
+ if (typeof ref === 'string') {
10
+ return;
11
+ }
12
+
13
+ if (typeof ref === 'function') {
14
+ return;
15
+ }
16
+
17
+ throw new MongooseError('Invalid ref at path "' + path + '". Got ' +
18
+ util.inspect(ref, { depth: 0 }));
19
+ }
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ const utils = require('../utils');
4
+
5
+ if (typeof jest !== 'undefined' && !process.env.SUPPRESS_JEST_WARNINGS) {
6
+ if (typeof window !== 'undefined') {
7
+ utils.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' +
8
+ 'with Jest\'s default jsdom test environment. Please make sure you read ' +
9
+ 'Mongoose\'s docs on configuring Jest to test Node.js apps: ' +
10
+ 'https://mongoosejs.com/docs/jest.html. Set the SUPPRESS_JEST_WARNINGS to true ' +
11
+ 'to hide this warning.');
12
+ }
13
+
14
+ if (typeof setTimeout.clock?.Date === 'function') {
15
+ utils.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' +
16
+ 'with Jest\'s mock timers enabled. Please make sure you read ' +
17
+ 'Mongoose\'s docs on configuring Jest to test Node.js apps: ' +
18
+ 'https://mongoosejs.com/docs/jest.html. Set the SUPPRESS_JEST_WARNINGS to true ' +
19
+ 'to hide this warning.');
20
+ }
21
+ }
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ const clone = require('./clone');
4
+ const MongooseError = require('../error/index');
5
+
6
+ function processConnectionOptions(uri, options) {
7
+ const opts = options ? options : {};
8
+ const readPreference = opts.readPreference
9
+ ? opts.readPreference
10
+ : getUriReadPreference(uri);
11
+
12
+ const clonedOpts = clone(opts);
13
+ const resolvedOpts = (readPreference && readPreference !== 'primary' && readPreference !== 'primaryPreferred')
14
+ ? resolveOptsConflicts(readPreference, clonedOpts)
15
+ : clonedOpts;
16
+
17
+ return resolvedOpts;
18
+ }
19
+
20
+ function resolveOptsConflicts(pref, opts) {
21
+ // don't silently override user-provided indexing options
22
+ if (setsIndexOptions(opts) && setsSecondaryRead(pref)) {
23
+ throwReadPreferenceError();
24
+ }
25
+
26
+ // if user has not explicitly set any auto-indexing options,
27
+ // we can silently default them all to false
28
+ else {
29
+ return defaultIndexOptsToFalse(opts);
30
+ }
31
+ }
32
+
33
+ function setsIndexOptions(opts) {
34
+ const configIdx = opts.config?.autoIndex;
35
+ const { autoCreate, autoIndex } = opts;
36
+ return !!(configIdx || autoCreate || autoIndex);
37
+ }
38
+
39
+ function setsSecondaryRead(prefString) {
40
+ return !!(prefString === 'secondary' || prefString === 'secondaryPreferred');
41
+ }
42
+
43
+ function getUriReadPreference(connectionString) {
44
+ const exp = /(?:&|\?)readPreference=(\w+)(?:&|$)/;
45
+ const match = exp.exec(connectionString);
46
+ return match ? match[1] : null;
47
+ }
48
+
49
+ function defaultIndexOptsToFalse(opts) {
50
+ opts.config = { autoIndex: false };
51
+ opts.autoCreate = false;
52
+ opts.autoIndex = false;
53
+ return opts;
54
+ }
55
+
56
+ function throwReadPreferenceError() {
57
+ throw new MongooseError(
58
+ 'MongoDB prohibits index creation on connections that read from ' +
59
+ 'non-primary replicas. Connections that set "readPreference" to "secondary" or ' +
60
+ '"secondaryPreferred" may not opt-in to the following connection options: ' +
61
+ 'autoCreate, autoIndex'
62
+ );
63
+ }
64
+
65
+ module.exports = processConnectionOptions;