@datanimbus/mongoose 6.13.10

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 (292) hide show
  1. package/.eslintrc.js +232 -0
  2. package/.mocharc.yml +4 -0
  3. package/LICENSE.md +22 -0
  4. package/README.md +387 -0
  5. package/SECURITY.md +1 -0
  6. package/browser.js +8 -0
  7. package/dist/browser.umd.js +2 -0
  8. package/index.js +63 -0
  9. package/lgtm.yml +12 -0
  10. package/lib/aggregate.js +1164 -0
  11. package/lib/browser.js +158 -0
  12. package/lib/browserDocument.js +101 -0
  13. package/lib/cast/boolean.js +32 -0
  14. package/lib/cast/date.js +41 -0
  15. package/lib/cast/decimal128.js +36 -0
  16. package/lib/cast/number.js +42 -0
  17. package/lib/cast/objectid.js +29 -0
  18. package/lib/cast/string.js +37 -0
  19. package/lib/cast.js +418 -0
  20. package/lib/collection.js +311 -0
  21. package/lib/connection.js +1574 -0
  22. package/lib/connectionstate.js +26 -0
  23. package/lib/cursor/AggregationCursor.js +380 -0
  24. package/lib/cursor/ChangeStream.js +154 -0
  25. package/lib/cursor/QueryCursor.js +538 -0
  26. package/lib/document.js +4771 -0
  27. package/lib/document_provider.js +30 -0
  28. package/lib/driver.js +15 -0
  29. package/lib/drivers/SPEC.md +4 -0
  30. package/lib/drivers/browser/ReadPreference.js +7 -0
  31. package/lib/drivers/browser/binary.js +14 -0
  32. package/lib/drivers/browser/decimal128.js +7 -0
  33. package/lib/drivers/browser/index.js +16 -0
  34. package/lib/drivers/browser/objectid.js +29 -0
  35. package/lib/drivers/node-mongodb-native/ReadPreference.js +47 -0
  36. package/lib/drivers/node-mongodb-native/binary.js +10 -0
  37. package/lib/drivers/node-mongodb-native/collection.js +460 -0
  38. package/lib/drivers/node-mongodb-native/connection.js +166 -0
  39. package/lib/drivers/node-mongodb-native/decimal128.js +7 -0
  40. package/lib/drivers/node-mongodb-native/index.js +12 -0
  41. package/lib/drivers/node-mongodb-native/objectid.js +16 -0
  42. package/lib/error/browserMissingSchema.js +28 -0
  43. package/lib/error/bulkWriteError.js +41 -0
  44. package/lib/error/cast.js +158 -0
  45. package/lib/error/disconnected.js +33 -0
  46. package/lib/error/divergentArray.js +38 -0
  47. package/lib/error/eachAsyncMultiError.js +41 -0
  48. package/lib/error/index.js +228 -0
  49. package/lib/error/messages.js +47 -0
  50. package/lib/error/missingSchema.js +31 -0
  51. package/lib/error/mongooseError.js +13 -0
  52. package/lib/error/notFound.js +45 -0
  53. package/lib/error/objectExpected.js +30 -0
  54. package/lib/error/objectParameter.js +30 -0
  55. package/lib/error/overwriteModel.js +30 -0
  56. package/lib/error/parallelSave.js +30 -0
  57. package/lib/error/parallelValidate.js +31 -0
  58. package/lib/error/serverSelection.js +61 -0
  59. package/lib/error/setOptionError.js +101 -0
  60. package/lib/error/strict.js +33 -0
  61. package/lib/error/strictPopulate.js +29 -0
  62. package/lib/error/syncIndexes.js +30 -0
  63. package/lib/error/validation.js +103 -0
  64. package/lib/error/validator.js +99 -0
  65. package/lib/error/version.js +36 -0
  66. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +39 -0
  67. package/lib/helpers/aggregate/stringifyFunctionOperators.js +50 -0
  68. package/lib/helpers/arrayDepth.js +33 -0
  69. package/lib/helpers/clone.js +177 -0
  70. package/lib/helpers/common.js +127 -0
  71. package/lib/helpers/cursor/eachAsync.js +222 -0
  72. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +16 -0
  73. package/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js +12 -0
  74. package/lib/helpers/discriminator/getConstructor.js +26 -0
  75. package/lib/helpers/discriminator/getDiscriminatorByValue.js +28 -0
  76. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +27 -0
  77. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +64 -0
  78. package/lib/helpers/document/applyDefaults.js +128 -0
  79. package/lib/helpers/document/cleanModifiedSubpaths.js +35 -0
  80. package/lib/helpers/document/compile.js +237 -0
  81. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +50 -0
  82. package/lib/helpers/document/handleSpreadDoc.js +35 -0
  83. package/lib/helpers/each.js +25 -0
  84. package/lib/helpers/error/combinePathErrors.js +22 -0
  85. package/lib/helpers/firstKey.js +8 -0
  86. package/lib/helpers/get.js +65 -0
  87. package/lib/helpers/getConstructorName.js +16 -0
  88. package/lib/helpers/getDefaultBulkwriteResult.js +27 -0
  89. package/lib/helpers/getFunctionName.js +10 -0
  90. package/lib/helpers/immediate.js +16 -0
  91. package/lib/helpers/indexes/applySchemaCollation.js +13 -0
  92. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +14 -0
  93. package/lib/helpers/indexes/getRelatedIndexes.js +59 -0
  94. package/lib/helpers/indexes/isDefaultIdIndex.js +18 -0
  95. package/lib/helpers/indexes/isIndexEqual.js +96 -0
  96. package/lib/helpers/indexes/isTextIndex.js +16 -0
  97. package/lib/helpers/isAsyncFunction.js +9 -0
  98. package/lib/helpers/isBsonType.js +16 -0
  99. package/lib/helpers/isMongooseObject.js +22 -0
  100. package/lib/helpers/isObject.js +16 -0
  101. package/lib/helpers/isPromise.js +6 -0
  102. package/lib/helpers/isSimpleValidator.js +22 -0
  103. package/lib/helpers/model/applyDefaultsToPOJO.js +52 -0
  104. package/lib/helpers/model/applyHooks.js +149 -0
  105. package/lib/helpers/model/applyMethods.js +70 -0
  106. package/lib/helpers/model/applyStaticHooks.js +71 -0
  107. package/lib/helpers/model/applyStatics.js +13 -0
  108. package/lib/helpers/model/castBulkWrite.js +240 -0
  109. package/lib/helpers/model/discriminator.js +218 -0
  110. package/lib/helpers/model/pushNestedArrayPaths.js +15 -0
  111. package/lib/helpers/once.js +12 -0
  112. package/lib/helpers/parallelLimit.js +55 -0
  113. package/lib/helpers/path/parentPaths.js +18 -0
  114. package/lib/helpers/path/setDottedPath.js +33 -0
  115. package/lib/helpers/pluralize.js +94 -0
  116. package/lib/helpers/populate/SkipPopulateValue.js +10 -0
  117. package/lib/helpers/populate/assignRawDocsToIdStructure.js +124 -0
  118. package/lib/helpers/populate/assignVals.js +337 -0
  119. package/lib/helpers/populate/createPopulateQueryFilter.js +97 -0
  120. package/lib/helpers/populate/getModelsMapForPopulate.js +756 -0
  121. package/lib/helpers/populate/getSchemaTypes.js +233 -0
  122. package/lib/helpers/populate/getVirtual.js +72 -0
  123. package/lib/helpers/populate/leanPopulateMap.js +7 -0
  124. package/lib/helpers/populate/lookupLocalFields.js +40 -0
  125. package/lib/helpers/populate/markArraySubdocsPopulated.js +47 -0
  126. package/lib/helpers/populate/modelNamesFromRefPath.js +68 -0
  127. package/lib/helpers/populate/removeDeselectedForeignField.js +31 -0
  128. package/lib/helpers/populate/validateRef.js +19 -0
  129. package/lib/helpers/printJestWarning.js +21 -0
  130. package/lib/helpers/printStrictQueryWarning.js +11 -0
  131. package/lib/helpers/processConnectionOptions.js +65 -0
  132. package/lib/helpers/projection/applyProjection.js +77 -0
  133. package/lib/helpers/projection/hasIncludedChildren.js +41 -0
  134. package/lib/helpers/projection/isDefiningProjection.js +18 -0
  135. package/lib/helpers/projection/isExclusive.js +35 -0
  136. package/lib/helpers/projection/isInclusive.js +38 -0
  137. package/lib/helpers/projection/isNestedProjection.js +8 -0
  138. package/lib/helpers/projection/isPathExcluded.js +40 -0
  139. package/lib/helpers/projection/isPathSelectedInclusive.js +28 -0
  140. package/lib/helpers/projection/isSubpath.js +14 -0
  141. package/lib/helpers/projection/parseProjection.js +33 -0
  142. package/lib/helpers/promiseOrCallback.js +55 -0
  143. package/lib/helpers/query/applyGlobalOption.js +29 -0
  144. package/lib/helpers/query/applyQueryMiddleware.js +79 -0
  145. package/lib/helpers/query/cast$expr.js +282 -0
  146. package/lib/helpers/query/castFilterPath.js +54 -0
  147. package/lib/helpers/query/castUpdate.js +560 -0
  148. package/lib/helpers/query/completeMany.js +52 -0
  149. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +90 -0
  150. package/lib/helpers/query/handleImmutable.js +28 -0
  151. package/lib/helpers/query/hasDollarKeys.js +23 -0
  152. package/lib/helpers/query/isOperator.js +14 -0
  153. package/lib/helpers/query/sanitizeFilter.js +38 -0
  154. package/lib/helpers/query/sanitizeProjection.js +14 -0
  155. package/lib/helpers/query/selectPopulatedFields.js +49 -0
  156. package/lib/helpers/query/trusted.js +13 -0
  157. package/lib/helpers/query/validOps.js +24 -0
  158. package/lib/helpers/query/wrapThunk.js +31 -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/applyWriteConcern.js +30 -0
  163. package/lib/helpers/schema/cleanPositionalOperators.js +12 -0
  164. package/lib/helpers/schema/getIndexes.js +164 -0
  165. package/lib/helpers/schema/getKeysInSchemaOrder.js +28 -0
  166. package/lib/helpers/schema/getPath.js +37 -0
  167. package/lib/helpers/schema/handleIdOption.js +20 -0
  168. package/lib/helpers/schema/handleTimestampOption.js +24 -0
  169. package/lib/helpers/schema/idGetter.js +32 -0
  170. package/lib/helpers/schema/merge.js +28 -0
  171. package/lib/helpers/schematype/handleImmutable.js +50 -0
  172. package/lib/helpers/setDefaultsOnInsert.js +132 -0
  173. package/lib/helpers/specialProperties.js +3 -0
  174. package/lib/helpers/symbols.js +20 -0
  175. package/lib/helpers/timers.js +3 -0
  176. package/lib/helpers/timestamps/setDocumentTimestamps.js +26 -0
  177. package/lib/helpers/timestamps/setupTimestamps.js +101 -0
  178. package/lib/helpers/topology/allServersUnknown.js +12 -0
  179. package/lib/helpers/topology/isAtlas.js +31 -0
  180. package/lib/helpers/topology/isSSLError.js +16 -0
  181. package/lib/helpers/update/applyTimestampsToChildren.js +193 -0
  182. package/lib/helpers/update/applyTimestampsToUpdate.js +117 -0
  183. package/lib/helpers/update/castArrayFilters.js +109 -0
  184. package/lib/helpers/update/modifiedPaths.js +33 -0
  185. package/lib/helpers/update/moveImmutableProperties.js +53 -0
  186. package/lib/helpers/update/removeUnusedArrayFilters.js +32 -0
  187. package/lib/helpers/update/updatedPathsByArrayFilter.js +27 -0
  188. package/lib/helpers/updateValidators.js +249 -0
  189. package/lib/index.js +1338 -0
  190. package/lib/internal.js +46 -0
  191. package/lib/model.js +5474 -0
  192. package/lib/options/PopulateOptions.js +36 -0
  193. package/lib/options/SchemaArrayOptions.js +78 -0
  194. package/lib/options/SchemaBufferOptions.js +38 -0
  195. package/lib/options/SchemaDateOptions.js +71 -0
  196. package/lib/options/SchemaDocumentArrayOptions.js +68 -0
  197. package/lib/options/SchemaMapOptions.js +43 -0
  198. package/lib/options/SchemaNumberOptions.js +101 -0
  199. package/lib/options/SchemaObjectIdOptions.js +64 -0
  200. package/lib/options/SchemaStringOptions.js +138 -0
  201. package/lib/options/SchemaSubdocumentOptions.js +42 -0
  202. package/lib/options/SchemaTypeOptions.js +244 -0
  203. package/lib/options/VirtualOptions.js +164 -0
  204. package/lib/options/propertyOptions.js +8 -0
  205. package/lib/options/removeOptions.js +14 -0
  206. package/lib/options/saveOptions.js +14 -0
  207. package/lib/options.js +15 -0
  208. package/lib/plugins/index.js +7 -0
  209. package/lib/plugins/removeSubdocs.js +31 -0
  210. package/lib/plugins/saveSubdocs.js +66 -0
  211. package/lib/plugins/sharding.js +83 -0
  212. package/lib/plugins/trackTransaction.js +92 -0
  213. package/lib/plugins/validateBeforeSave.js +45 -0
  214. package/lib/promise_provider.js +49 -0
  215. package/lib/query.js +5982 -0
  216. package/lib/queryhelpers.js +353 -0
  217. package/lib/schema/DocumentArrayElement.js +100 -0
  218. package/lib/schema/SubdocumentPath.js +369 -0
  219. package/lib/schema/array.js +663 -0
  220. package/lib/schema/boolean.js +267 -0
  221. package/lib/schema/buffer.js +269 -0
  222. package/lib/schema/date.js +404 -0
  223. package/lib/schema/decimal128.js +210 -0
  224. package/lib/schema/documentarray.js +598 -0
  225. package/lib/schema/index.js +39 -0
  226. package/lib/schema/map.js +84 -0
  227. package/lib/schema/mixed.js +132 -0
  228. package/lib/schema/number.js +438 -0
  229. package/lib/schema/objectid.js +295 -0
  230. package/lib/schema/operators/bitwise.js +38 -0
  231. package/lib/schema/operators/exists.js +12 -0
  232. package/lib/schema/operators/geospatial.js +107 -0
  233. package/lib/schema/operators/helpers.js +32 -0
  234. package/lib/schema/operators/text.js +39 -0
  235. package/lib/schema/operators/type.js +20 -0
  236. package/lib/schema/string.js +694 -0
  237. package/lib/schema/symbols.js +5 -0
  238. package/lib/schema/uuid.js +334 -0
  239. package/lib/schema.js +2665 -0
  240. package/lib/schematype.js +1727 -0
  241. package/lib/statemachine.js +207 -0
  242. package/lib/types/ArraySubdocument.js +189 -0
  243. package/lib/types/DocumentArray/index.js +113 -0
  244. package/lib/types/DocumentArray/isMongooseDocumentArray.js +5 -0
  245. package/lib/types/DocumentArray/methods/index.js +383 -0
  246. package/lib/types/array/index.js +116 -0
  247. package/lib/types/array/isMongooseArray.js +5 -0
  248. package/lib/types/array/methods/index.js +1014 -0
  249. package/lib/types/buffer.js +277 -0
  250. package/lib/types/decimal128.js +13 -0
  251. package/lib/types/index.js +20 -0
  252. package/lib/types/map.js +354 -0
  253. package/lib/types/objectid.js +41 -0
  254. package/lib/types/subdocument.js +432 -0
  255. package/lib/utils.js +1011 -0
  256. package/lib/validoptions.js +36 -0
  257. package/lib/virtualtype.js +175 -0
  258. package/package.json +164 -0
  259. package/scripts/build-browser.js +18 -0
  260. package/scripts/create-tarball.js +7 -0
  261. package/scripts/generateSearch.js +154 -0
  262. package/scripts/tsc-diagnostics-check.js +15 -0
  263. package/tools/auth.js +31 -0
  264. package/tools/repl.js +35 -0
  265. package/tools/sharded.js +46 -0
  266. package/tsconfig.json +9 -0
  267. package/types/aggregate.d.ts +174 -0
  268. package/types/augmentations.d.ts +9 -0
  269. package/types/callback.d.ts +8 -0
  270. package/types/collection.d.ts +44 -0
  271. package/types/connection.d.ts +242 -0
  272. package/types/cursor.d.ts +62 -0
  273. package/types/document.d.ts +266 -0
  274. package/types/error.d.ts +138 -0
  275. package/types/expressions.d.ts +2936 -0
  276. package/types/helpers.d.ts +32 -0
  277. package/types/index.d.ts +627 -0
  278. package/types/indexes.d.ts +98 -0
  279. package/types/inferschematype.d.ts +228 -0
  280. package/types/middlewares.d.ts +32 -0
  281. package/types/models.d.ts +488 -0
  282. package/types/mongooseoptions.d.ts +206 -0
  283. package/types/pipelinestage.d.ts +297 -0
  284. package/types/populate.d.ts +45 -0
  285. package/types/query.d.ts +659 -0
  286. package/types/schemaoptions.d.ts +231 -0
  287. package/types/schematypes.d.ts +478 -0
  288. package/types/session.d.ts +36 -0
  289. package/types/types.d.ts +104 -0
  290. package/types/utility.d.ts +43 -0
  291. package/types/validation.d.ts +34 -0
  292. package/types/virtuals.d.ts +14 -0
@@ -0,0 +1,560 @@
1
+ 'use strict';
2
+
3
+ const CastError = require('../../error/cast');
4
+ const MongooseError = require('../../error/mongooseError');
5
+ const StrictModeError = require('../../error/strict');
6
+ const ValidationError = require('../../error/validation');
7
+ const castNumber = require('../../cast/number');
8
+ const cast = require('../../cast');
9
+ const getConstructorName = require('../getConstructorName');
10
+ const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath');
11
+ const handleImmutable = require('./handleImmutable');
12
+ const moveImmutableProperties = require('../update/moveImmutableProperties');
13
+ const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol;
14
+ const setDottedPath = require('../path/setDottedPath');
15
+ const utils = require('../../utils');
16
+
17
+ /**
18
+ * Casts an update op based on the given schema
19
+ *
20
+ * @param {Schema} schema
21
+ * @param {Object} obj
22
+ * @param {Object} [options]
23
+ * @param {Boolean} [options.overwrite] defaults to false
24
+ * @param {Boolean|String} [options.strict] defaults to true
25
+ * @param {Query} context passed to setters
26
+ * @return {Boolean} true iff the update is non-empty
27
+ * @api private
28
+ */
29
+ module.exports = function castUpdate(schema, obj, options, context, filter) {
30
+ if (obj == null) {
31
+ return undefined;
32
+ }
33
+ options = options || {};
34
+ // Update pipeline
35
+ if (Array.isArray(obj)) {
36
+ const len = obj.length;
37
+ for (let i = 0; i < len; ++i) {
38
+ const ops = Object.keys(obj[i]);
39
+ for (const op of ops) {
40
+ obj[i][op] = castPipelineOperator(op, obj[i][op]);
41
+ }
42
+ }
43
+ return obj;
44
+ }
45
+
46
+ if (options.upsert && !options.overwrite) {
47
+ moveImmutableProperties(schema, obj, context);
48
+ }
49
+
50
+ const ops = Object.keys(obj);
51
+ let i = ops.length;
52
+ const ret = {};
53
+ let val;
54
+ let hasDollarKey = false;
55
+ const overwrite = options.overwrite;
56
+
57
+ filter = filter || {};
58
+ while (i--) {
59
+ const op = ops[i];
60
+ // if overwrite is set, don't do any of the special $set stuff
61
+ if (op[0] !== '$' && !overwrite) {
62
+ // fix up $set sugar
63
+ if (!ret.$set) {
64
+ if (obj.$set) {
65
+ ret.$set = obj.$set;
66
+ } else {
67
+ ret.$set = {};
68
+ }
69
+ }
70
+ ret.$set[op] = obj[op];
71
+ ops.splice(i, 1);
72
+ if (!~ops.indexOf('$set')) ops.push('$set');
73
+ } else if (op === '$set') {
74
+ if (!ret.$set) {
75
+ ret[op] = obj[op];
76
+ }
77
+ } else {
78
+ ret[op] = obj[op];
79
+ }
80
+ }
81
+ // cast each value
82
+ i = ops.length;
83
+ while (i--) {
84
+ const op = ops[i];
85
+ val = ret[op];
86
+ hasDollarKey = hasDollarKey || op.startsWith('$');
87
+
88
+ if (val &&
89
+ typeof val === 'object' &&
90
+ !Buffer.isBuffer(val) &&
91
+ (!overwrite || hasDollarKey)) {
92
+ walkUpdatePath(schema, val, op, options, context, filter);
93
+ } else if (overwrite && ret && typeof ret === 'object') {
94
+ walkUpdatePath(schema, ret, '$set', options, context, filter);
95
+ } else {
96
+ const msg = 'Invalid atomic update value for ' + op + '. '
97
+ + 'Expected an object, received ' + typeof val;
98
+ throw new Error(msg);
99
+ }
100
+
101
+ if (op.startsWith('$') && utils.isEmptyObject(val)) {
102
+ delete ret[op];
103
+ }
104
+ }
105
+
106
+ if (Object.keys(ret).length === 0 &&
107
+ options.upsert &&
108
+ Object.keys(filter).length > 0) {
109
+ // Trick the driver into allowing empty upserts to work around
110
+ // https://github.com/mongodb/node-mongodb-native/pull/2490
111
+ return { $setOnInsert: filter };
112
+ }
113
+ return ret;
114
+ };
115
+
116
+ /*!
117
+ * ignore
118
+ */
119
+
120
+ function castPipelineOperator(op, val) {
121
+ if (op === '$unset') {
122
+ if (typeof val !== 'string' && (!Array.isArray(val) || val.find(v => typeof v !== 'string'))) {
123
+ throw new MongooseError('Invalid $unset in pipeline, must be ' +
124
+ ' a string or an array of strings');
125
+ }
126
+ return val;
127
+ }
128
+ if (op === '$project') {
129
+ if (val == null || typeof val !== 'object') {
130
+ throw new MongooseError('Invalid $project in pipeline, must be an object');
131
+ }
132
+ return val;
133
+ }
134
+ if (op === '$addFields' || op === '$set') {
135
+ if (val == null || typeof val !== 'object') {
136
+ throw new MongooseError('Invalid ' + op + ' in pipeline, must be an object');
137
+ }
138
+ return val;
139
+ } else if (op === '$replaceRoot' || op === '$replaceWith') {
140
+ if (val == null || typeof val !== 'object') {
141
+ throw new MongooseError('Invalid ' + op + ' in pipeline, must be an object');
142
+ }
143
+ return val;
144
+ }
145
+
146
+ throw new MongooseError('Invalid update pipeline operator: "' + op + '"');
147
+ }
148
+
149
+ /**
150
+ * Walk each path of obj and cast its values
151
+ * according to its schema.
152
+ *
153
+ * @param {Schema} schema
154
+ * @param {Object} obj part of a query
155
+ * @param {String} op the atomic operator ($pull, $set, etc)
156
+ * @param {Object} [options]
157
+ * @param {Boolean|String} [options.strict]
158
+ * @param {Query} context
159
+ * @param {Object} filter
160
+ * @param {String} pref path prefix (internal only)
161
+ * @return {Bool} true if this path has keys to update
162
+ * @api private
163
+ */
164
+
165
+ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
166
+ const strict = options.strict;
167
+ const prefix = pref ? pref + '.' : '';
168
+ const keys = Object.keys(obj);
169
+ let i = keys.length;
170
+ let hasKeys = false;
171
+ let schematype;
172
+ let key;
173
+ let val;
174
+
175
+ let aggregatedError = null;
176
+
177
+ const strictMode = strict != null ? strict : schema.options.strict;
178
+
179
+ while (i--) {
180
+ key = keys[i];
181
+ val = obj[key];
182
+
183
+ // `$pull` is special because we need to cast the RHS as a query, not as
184
+ // an update.
185
+ if (op === '$pull') {
186
+ schematype = schema._getSchema(prefix + key);
187
+ if (schematype != null && schematype.schema != null) {
188
+ obj[key] = cast(schematype.schema, obj[key], options, context);
189
+ hasKeys = true;
190
+ continue;
191
+ }
192
+ }
193
+
194
+ const discriminatorKey = (prefix ? prefix + key : key);
195
+ if (
196
+ schema.discriminatorMapping != null &&
197
+ discriminatorKey === schema.options.discriminatorKey &&
198
+ schema.discriminatorMapping.value !== obj[key] &&
199
+ !options.overwriteDiscriminatorKey
200
+ ) {
201
+ if (strictMode === 'throw') {
202
+ const err = new Error('Can\'t modify discriminator key "' + discriminatorKey + '" on discriminator model');
203
+ aggregatedError = _appendError(err, context, discriminatorKey, aggregatedError);
204
+ continue;
205
+ } else if (strictMode) {
206
+ delete obj[key];
207
+ continue;
208
+ }
209
+ }
210
+
211
+ if (getConstructorName(val) === 'Object') {
212
+ // watch for embedded doc schemas
213
+ schematype = schema._getSchema(prefix + key);
214
+
215
+ if (schematype == null) {
216
+ const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options);
217
+ if (_res.schematype != null) {
218
+ schematype = _res.schematype;
219
+ }
220
+ }
221
+
222
+ if (op !== '$setOnInsert' &&
223
+ !options.overwrite &&
224
+ handleImmutable(schematype, strict, obj, key, prefix + key, context)) {
225
+ continue;
226
+ }
227
+
228
+ if (schematype && schematype.caster && op in castOps) {
229
+ // embedded doc schema
230
+ if ('$each' in val) {
231
+ hasKeys = true;
232
+ try {
233
+ obj[key] = {
234
+ $each: castUpdateVal(schematype, val.$each, op, key, context, prefix + key)
235
+ };
236
+ } catch (error) {
237
+ aggregatedError = _appendError(error, context, key, aggregatedError);
238
+ }
239
+
240
+ if (val.$slice != null) {
241
+ obj[key].$slice = val.$slice | 0;
242
+ }
243
+
244
+ if (val.$sort) {
245
+ obj[key].$sort = val.$sort;
246
+ }
247
+
248
+ if (val.$position != null) {
249
+ obj[key].$position = castNumber(val.$position);
250
+ }
251
+ } else {
252
+ if (schematype != null && schematype.$isSingleNested) {
253
+ const _strict = strict == null ? schematype.schema.options.strict : strict;
254
+ try {
255
+ obj[key] = schematype.castForQuery(val, context, { strict: _strict });
256
+ } catch (error) {
257
+ aggregatedError = _appendError(error, context, key, aggregatedError);
258
+ }
259
+ } else {
260
+ try {
261
+ obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
262
+ } catch (error) {
263
+ aggregatedError = _appendError(error, context, key, aggregatedError);
264
+ }
265
+ }
266
+
267
+ if (obj[key] === void 0) {
268
+ delete obj[key];
269
+ continue;
270
+ }
271
+
272
+ hasKeys = true;
273
+ }
274
+ } else if ((op === '$currentDate') || (op in castOps && schematype)) {
275
+ // $currentDate can take an object
276
+ try {
277
+ obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
278
+ } catch (error) {
279
+ aggregatedError = _appendError(error, context, key, aggregatedError);
280
+ }
281
+
282
+ if (obj[key] === void 0) {
283
+ delete obj[key];
284
+ continue;
285
+ }
286
+
287
+ hasKeys = true;
288
+ } else {
289
+ const pathToCheck = (prefix + key);
290
+ const v = schema._getPathType(pathToCheck);
291
+ let _strict = strict;
292
+ if (v && v.schema && _strict == null) {
293
+ _strict = v.schema.options.strict;
294
+ }
295
+
296
+ if (v.pathType === 'undefined') {
297
+ if (_strict === 'throw') {
298
+ throw new StrictModeError(pathToCheck);
299
+ } else if (_strict) {
300
+ delete obj[key];
301
+ continue;
302
+ }
303
+ }
304
+
305
+ // gh-2314
306
+ // we should be able to set a schema-less field
307
+ // to an empty object literal
308
+ hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) ||
309
+ (utils.isObject(val) && Object.keys(val).length === 0);
310
+ }
311
+ } else {
312
+ const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ?
313
+ pref : prefix + key;
314
+ schematype = schema._getSchema(checkPath);
315
+
316
+ // You can use `$setOnInsert` with immutable keys
317
+ if (op !== '$setOnInsert' &&
318
+ !options.overwrite &&
319
+ handleImmutable(schematype, strict, obj, key, prefix + key, context)) {
320
+ continue;
321
+ }
322
+
323
+ let pathDetails = schema._getPathType(checkPath);
324
+
325
+ // If no schema type, check for embedded discriminators because the
326
+ // filter or update may imply an embedded discriminator type. See #8378
327
+ if (schematype == null) {
328
+ const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, checkPath, options);
329
+ if (_res.schematype != null) {
330
+ schematype = _res.schematype;
331
+ pathDetails = _res.type;
332
+ }
333
+ }
334
+
335
+ let isStrict = strict;
336
+ if (pathDetails && pathDetails.schema && strict == null) {
337
+ isStrict = pathDetails.schema.options.strict;
338
+ }
339
+
340
+ const skip = isStrict &&
341
+ !schematype &&
342
+ !/real|nested/.test(pathDetails.pathType);
343
+
344
+ if (skip) {
345
+ // Even if strict is `throw`, avoid throwing an error because of
346
+ // virtuals because of #6731
347
+ if (isStrict === 'throw' && schema.virtuals[checkPath] == null) {
348
+ throw new StrictModeError(prefix + key);
349
+ } else {
350
+ delete obj[key];
351
+ }
352
+ } else {
353
+ // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking
354
+ // improving this.
355
+ if (op === '$rename') {
356
+ hasKeys = true;
357
+ continue;
358
+ }
359
+
360
+ try {
361
+ if (prefix.length === 0 || key.indexOf('.') === -1) {
362
+ obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
363
+ } else {
364
+ // Setting a nested dotted path that's in the schema. We don't allow paths with '.' in
365
+ // a schema, so replace the dotted path with a nested object to avoid ending up with
366
+ // dotted properties in the updated object. See (gh-10200)
367
+ setDottedPath(obj, key, castUpdateVal(schematype, val, op, key, context, prefix + key));
368
+ delete obj[key];
369
+ }
370
+ } catch (error) {
371
+ aggregatedError = _appendError(error, context, key, aggregatedError);
372
+ }
373
+
374
+ if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') {
375
+ if (schematype &&
376
+ schematype.caster &&
377
+ !schematype.caster.$isMongooseArray &&
378
+ !schematype.caster[schemaMixedSymbol]) {
379
+ obj[key] = { $each: obj[key] };
380
+ }
381
+ }
382
+
383
+ if (obj[key] === void 0) {
384
+ delete obj[key];
385
+ continue;
386
+ }
387
+
388
+ hasKeys = true;
389
+ }
390
+ }
391
+ }
392
+
393
+ if (aggregatedError != null) {
394
+ throw aggregatedError;
395
+ }
396
+
397
+ return hasKeys;
398
+ }
399
+
400
+ /*!
401
+ * ignore
402
+ */
403
+
404
+ function _appendError(error, query, key, aggregatedError) {
405
+ if (typeof query !== 'object' || !query.options.multipleCastError) {
406
+ throw error;
407
+ }
408
+ aggregatedError = aggregatedError || new ValidationError();
409
+ aggregatedError.addError(key, error);
410
+ return aggregatedError;
411
+ }
412
+
413
+ /**
414
+ * These operators should be cast to numbers instead
415
+ * of their path schema type.
416
+ * @api private
417
+ */
418
+
419
+ const numberOps = {
420
+ $pop: 1,
421
+ $inc: 1
422
+ };
423
+
424
+ /**
425
+ * These ops require no casting because the RHS doesn't do anything.
426
+ * @api private
427
+ */
428
+
429
+ const noCastOps = {
430
+ $unset: 1
431
+ };
432
+
433
+ /**
434
+ * These operators require casting docs
435
+ * to real Documents for Update operations.
436
+ * @api private
437
+ */
438
+
439
+ const castOps = {
440
+ $push: 1,
441
+ $addToSet: 1,
442
+ $set: 1,
443
+ $setOnInsert: 1
444
+ };
445
+
446
+ /*!
447
+ * ignore
448
+ */
449
+
450
+ const overwriteOps = {
451
+ $set: 1,
452
+ $setOnInsert: 1
453
+ };
454
+
455
+ /**
456
+ * Casts `val` according to `schema` and atomic `op`.
457
+ *
458
+ * @param {SchemaType} schema
459
+ * @param {Object} val
460
+ * @param {String} op the atomic operator ($pull, $set, etc)
461
+ * @param {String} $conditional
462
+ * @param {Query} context
463
+ * @param {String} path
464
+ * @api private
465
+ */
466
+
467
+ function castUpdateVal(schema, val, op, $conditional, context, path) {
468
+ if (!schema) {
469
+ // non-existing schema path
470
+ if (op in numberOps) {
471
+ try {
472
+ return castNumber(val);
473
+ } catch (err) {
474
+ throw new CastError('number', val, path);
475
+ }
476
+ }
477
+ return val;
478
+ }
479
+
480
+ // console.log('CastUpdateVal', path, op, val, schema);
481
+
482
+ const cond = schema.caster && op in castOps &&
483
+ (utils.isObject(val) || Array.isArray(val));
484
+ if (cond && !overwriteOps[op]) {
485
+ // Cast values for ops that add data to MongoDB.
486
+ // Ensures embedded documents get ObjectIds etc.
487
+ let schemaArrayDepth = 0;
488
+ let cur = schema;
489
+ while (cur.$isMongooseArray) {
490
+ ++schemaArrayDepth;
491
+ cur = cur.caster;
492
+ }
493
+ let arrayDepth = 0;
494
+ let _val = val;
495
+ while (Array.isArray(_val)) {
496
+ ++arrayDepth;
497
+ _val = _val[0];
498
+ }
499
+
500
+ const additionalNesting = schemaArrayDepth - arrayDepth;
501
+ while (arrayDepth < schemaArrayDepth) {
502
+ val = [val];
503
+ ++arrayDepth;
504
+ }
505
+
506
+ let tmp = schema.applySetters(Array.isArray(val) ? val : [val], context);
507
+
508
+ for (let i = 0; i < additionalNesting; ++i) {
509
+ tmp = tmp[0];
510
+ }
511
+ return tmp;
512
+ }
513
+
514
+ if (op in noCastOps) {
515
+ return val;
516
+ }
517
+ if (op in numberOps) {
518
+ // Null and undefined not allowed for $pop, $inc
519
+ if (val == null) {
520
+ throw new CastError('number', val, schema.path);
521
+ }
522
+ if (op === '$inc') {
523
+ // Support `$inc` with long, int32, etc. (gh-4283)
524
+ return schema.castForQueryWrapper({
525
+ val: val,
526
+ context: context
527
+ });
528
+ }
529
+ try {
530
+ return castNumber(val);
531
+ } catch (error) {
532
+ throw new CastError('number', val, schema.path);
533
+ }
534
+ }
535
+ if (op === '$currentDate') {
536
+ if (typeof val === 'object') {
537
+ return { $type: val.$type };
538
+ }
539
+ return Boolean(val);
540
+ }
541
+
542
+ if (/^\$/.test($conditional)) {
543
+ return schema.castForQueryWrapper({
544
+ $conditional: $conditional,
545
+ val: val,
546
+ context: context
547
+ });
548
+ }
549
+
550
+ if (overwriteOps[op]) {
551
+ return schema.castForQueryWrapper({
552
+ val: val,
553
+ context: context,
554
+ $skipQueryCastForUpdate: val != null && schema.$isMongooseArray && schema.$fullPath != null && !schema.$fullPath.match(/\d+$/),
555
+ $applySetters: schema[schemaMixedSymbol] != null
556
+ });
557
+ }
558
+
559
+ return schema.castForQueryWrapper({ val: val, context: context });
560
+ }
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ const helpers = require('../../queryhelpers');
4
+ const immediate = require('../immediate');
5
+
6
+ module.exports = completeMany;
7
+
8
+ /**
9
+ * Given a model and an array of docs, hydrates all the docs to be instances
10
+ * of the model. Used to initialize docs returned from the db from `find()`
11
+ *
12
+ * @param {Model} model
13
+ * @param {Array} docs
14
+ * @param {Object} fields the projection used, including `select` from schemas
15
+ * @param {Object} userProvidedFields the user-specified projection
16
+ * @param {Object} [opts]
17
+ * @param {Array} [opts.populated]
18
+ * @param {ClientSession} [opts.session]
19
+ * @param {Function} callback
20
+ * @api private
21
+ */
22
+
23
+ function completeMany(model, docs, fields, userProvidedFields, opts, callback) {
24
+ const arr = [];
25
+ let count = docs.length;
26
+ const len = count;
27
+ let error = null;
28
+
29
+ function init(_error) {
30
+ if (_error != null) {
31
+ error = error || _error;
32
+ }
33
+ if (error != null) {
34
+ --count || immediate(() => callback(error));
35
+ return;
36
+ }
37
+ --count || immediate(() => callback(error, arr));
38
+ }
39
+
40
+ for (let i = 0; i < len; ++i) {
41
+ arr[i] = helpers.createModel(model, docs[i], fields, userProvidedFields);
42
+ try {
43
+ arr[i].$init(docs[i], opts, init);
44
+ } catch (error) {
45
+ init(error);
46
+ }
47
+
48
+ if (opts.session != null) {
49
+ arr[i].$session(opts.session);
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,90 @@
1
+ 'use strict';
2
+
3
+ const cleanPositionalOperators = require('../schema/cleanPositionalOperators');
4
+ const get = require('../get');
5
+ const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
6
+ const updatedPathsByArrayFilter = require('../update/updatedPathsByArrayFilter');
7
+
8
+ /**
9
+ * Like `schema.path()`, except with a document, because impossible to
10
+ * determine path type without knowing the embedded discriminator key.
11
+ * @param {Schema} schema
12
+ * @param {Object} [update]
13
+ * @param {Object} [filter]
14
+ * @param {String} path
15
+ * @param {Object} [options]
16
+ * @api private
17
+ */
18
+
19
+ module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path, options) {
20
+ const parts = path.split('.');
21
+ let schematype = null;
22
+ let type = 'adhocOrUndefined';
23
+
24
+ filter = filter || {};
25
+ update = update || {};
26
+ const arrayFilters = options != null && Array.isArray(options.arrayFilters) ?
27
+ options.arrayFilters : [];
28
+ const updatedPathsByFilter = updatedPathsByArrayFilter(update);
29
+
30
+ for (let i = 0; i < parts.length; ++i) {
31
+ const subpath = cleanPositionalOperators(parts.slice(0, i + 1).join('.'));
32
+ schematype = schema.path(subpath);
33
+ if (schematype == null) {
34
+ continue;
35
+ }
36
+
37
+ type = schema.pathType(subpath);
38
+ if ((schematype.$isSingleNested || schematype.$isMongooseDocumentArrayElement) &&
39
+ schematype.schema.discriminators != null) {
40
+ const key = get(schematype, 'schema.options.discriminatorKey');
41
+ const discriminatorValuePath = subpath + '.' + key;
42
+ const discriminatorFilterPath =
43
+ discriminatorValuePath.replace(/\.\d+\./, '.');
44
+ let discriminatorKey = null;
45
+
46
+ if (discriminatorValuePath in filter) {
47
+ discriminatorKey = filter[discriminatorValuePath];
48
+ }
49
+ if (discriminatorFilterPath in filter) {
50
+ discriminatorKey = filter[discriminatorFilterPath];
51
+ }
52
+
53
+ const wrapperPath = subpath.replace(/\.\d+$/, '');
54
+ if (schematype.$isMongooseDocumentArrayElement &&
55
+ get(filter[wrapperPath], '$elemMatch.' + key) != null) {
56
+ discriminatorKey = filter[wrapperPath].$elemMatch[key];
57
+ }
58
+
59
+ if (discriminatorValuePath in update) {
60
+ discriminatorKey = update[discriminatorValuePath];
61
+ }
62
+
63
+ for (const filterKey of Object.keys(updatedPathsByFilter)) {
64
+ const schemaKey = updatedPathsByFilter[filterKey] + '.' + key;
65
+ const arrayFilterKey = filterKey + '.' + key;
66
+ if (schemaKey === discriminatorFilterPath) {
67
+ const filter = arrayFilters.find(filter => filter.hasOwnProperty(arrayFilterKey));
68
+ if (filter != null) {
69
+ discriminatorKey = filter[arrayFilterKey];
70
+ }
71
+ }
72
+ }
73
+
74
+ if (discriminatorKey == null) {
75
+ continue;
76
+ }
77
+
78
+ const discriminatorSchema = getDiscriminatorByValue(schematype.caster.discriminators, discriminatorKey).schema;
79
+
80
+ const rest = parts.slice(i + 1).join('.');
81
+ schematype = discriminatorSchema.path(rest);
82
+ if (schematype != null) {
83
+ type = discriminatorSchema._getPathType(rest);
84
+ break;
85
+ }
86
+ }
87
+ }
88
+
89
+ return { type: type, schematype: schematype };
90
+ };