@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,240 @@
1
+ 'use strict';
2
+
3
+ const getDiscriminatorByValue = require('../../helpers/discriminator/getDiscriminatorByValue');
4
+ const applyTimestampsToChildren = require('../update/applyTimestampsToChildren');
5
+ const applyTimestampsToUpdate = require('../update/applyTimestampsToUpdate');
6
+ const cast = require('../../cast');
7
+ const castUpdate = require('../query/castUpdate');
8
+ const setDefaultsOnInsert = require('../setDefaultsOnInsert');
9
+
10
+ /**
11
+ * Given a model and a bulkWrite op, return a thunk that handles casting and
12
+ * validating the individual op.
13
+ * @param {Model} originalModel
14
+ * @param {Object} op
15
+ * @param {Object} [options]
16
+ * @api private
17
+ */
18
+
19
+ module.exports = function castBulkWrite(originalModel, op, options) {
20
+ const now = originalModel.base.now();
21
+
22
+ if (op['insertOne']) {
23
+ return (callback) => {
24
+ const model = decideModelByObject(originalModel, op['insertOne']['document']);
25
+
26
+ const doc = new model(op['insertOne']['document']);
27
+ if (model.schema.options.timestamps && options.timestamps !== false) {
28
+ doc.initializeTimestamps();
29
+ }
30
+ if (options.session != null) {
31
+ doc.$session(options.session);
32
+ }
33
+ op['insertOne']['document'] = doc;
34
+
35
+ if (options.skipValidation || op['insertOne'].skipValidation) {
36
+ callback(null);
37
+ return;
38
+ }
39
+
40
+ op['insertOne']['document'].$validate({ __noPromise: true }, function(error) {
41
+ if (error) {
42
+ return callback(error, null);
43
+ }
44
+ callback(null);
45
+ });
46
+ };
47
+ } else if (op['updateOne']) {
48
+ return (callback) => {
49
+ try {
50
+ if (!op['updateOne']['filter']) {
51
+ throw new Error('Must provide a filter object.');
52
+ }
53
+ if (!op['updateOne']['update']) {
54
+ throw new Error('Must provide an update object.');
55
+ }
56
+
57
+ const model = decideModelByObject(originalModel, op['updateOne']['filter']);
58
+ const schema = model.schema;
59
+ const strict = options.strict != null ? options.strict : model.schema.options.strict;
60
+
61
+ _addDiscriminatorToObject(schema, op['updateOne']['filter']);
62
+
63
+ if (model.schema.$timestamps != null && op['updateOne'].timestamps !== false) {
64
+ const createdAt = model.schema.$timestamps.createdAt;
65
+ const updatedAt = model.schema.$timestamps.updatedAt;
66
+ applyTimestampsToUpdate(now, createdAt, updatedAt, op['updateOne']['update'], {});
67
+ }
68
+
69
+ applyTimestampsToChildren(now, op['updateOne']['update'], model.schema);
70
+
71
+ if (op['updateOne'].setDefaultsOnInsert !== false) {
72
+ setDefaultsOnInsert(op['updateOne']['filter'], model.schema, op['updateOne']['update'], {
73
+ setDefaultsOnInsert: true,
74
+ upsert: op['updateOne'].upsert
75
+ });
76
+ }
77
+
78
+ op['updateOne']['filter'] = cast(model.schema, op['updateOne']['filter'], {
79
+ strict: strict,
80
+ upsert: op['updateOne'].upsert
81
+ });
82
+
83
+ op['updateOne']['update'] = castUpdate(model.schema, op['updateOne']['update'], {
84
+ strict: strict,
85
+ overwrite: false,
86
+ upsert: op['updateOne'].upsert
87
+ }, model, op['updateOne']['filter']);
88
+ } catch (error) {
89
+ return callback(error, null);
90
+ }
91
+
92
+ callback(null);
93
+ };
94
+ } else if (op['updateMany']) {
95
+ return (callback) => {
96
+ try {
97
+ if (!op['updateMany']['filter']) {
98
+ throw new Error('Must provide a filter object.');
99
+ }
100
+ if (!op['updateMany']['update']) {
101
+ throw new Error('Must provide an update object.');
102
+ }
103
+
104
+ const model = decideModelByObject(originalModel, op['updateMany']['filter']);
105
+ const schema = model.schema;
106
+ const strict = options.strict != null ? options.strict : model.schema.options.strict;
107
+
108
+ if (op['updateMany'].setDefaultsOnInsert !== false) {
109
+ setDefaultsOnInsert(op['updateMany']['filter'], model.schema, op['updateMany']['update'], {
110
+ setDefaultsOnInsert: true,
111
+ upsert: op['updateMany'].upsert
112
+ });
113
+ }
114
+
115
+ if (model.schema.$timestamps != null && op['updateMany'].timestamps !== false) {
116
+ const createdAt = model.schema.$timestamps.createdAt;
117
+ const updatedAt = model.schema.$timestamps.updatedAt;
118
+ applyTimestampsToUpdate(now, createdAt, updatedAt, op['updateMany']['update'], {});
119
+ }
120
+
121
+ applyTimestampsToChildren(now, op['updateMany']['update'], model.schema);
122
+
123
+ _addDiscriminatorToObject(schema, op['updateMany']['filter']);
124
+
125
+ op['updateMany']['filter'] = cast(model.schema, op['updateMany']['filter'], {
126
+ strict: strict,
127
+ upsert: op['updateMany'].upsert
128
+ });
129
+
130
+ op['updateMany']['update'] = castUpdate(model.schema, op['updateMany']['update'], {
131
+ strict: strict,
132
+ overwrite: false,
133
+ upsert: op['updateMany'].upsert
134
+ }, model, op['updateMany']['filter']);
135
+ } catch (error) {
136
+ return callback(error, null);
137
+ }
138
+
139
+ callback(null);
140
+ };
141
+ } else if (op['replaceOne']) {
142
+ return (callback) => {
143
+ const model = decideModelByObject(originalModel, op['replaceOne']['filter']);
144
+ const schema = model.schema;
145
+ const strict = options.strict != null ? options.strict : model.schema.options.strict;
146
+
147
+ _addDiscriminatorToObject(schema, op['replaceOne']['filter']);
148
+ try {
149
+ op['replaceOne']['filter'] = cast(model.schema, op['replaceOne']['filter'], {
150
+ strict: strict,
151
+ upsert: op['replaceOne'].upsert
152
+ });
153
+ } catch (error) {
154
+ return callback(error, null);
155
+ }
156
+
157
+ // set `skipId`, otherwise we get "_id field cannot be changed"
158
+ const doc = new model(op['replaceOne']['replacement'], strict, true);
159
+ if (model.schema.options.timestamps) {
160
+ doc.initializeTimestamps();
161
+ }
162
+ if (options.session != null) {
163
+ doc.$session(options.session);
164
+ }
165
+ op['replaceOne']['replacement'] = doc;
166
+
167
+ if (options.skipValidation || op['replaceOne'].skipValidation) {
168
+ op['replaceOne']['replacement'] = op['replaceOne']['replacement'].toBSON();
169
+ callback(null);
170
+ return;
171
+ }
172
+
173
+ op['replaceOne']['replacement'].$validate({ __noPromise: true }, function(error) {
174
+ if (error) {
175
+ return callback(error, null);
176
+ }
177
+ op['replaceOne']['replacement'] = op['replaceOne']['replacement'].toBSON();
178
+ callback(null);
179
+ });
180
+ };
181
+ } else if (op['deleteOne']) {
182
+ return (callback) => {
183
+ const model = decideModelByObject(originalModel, op['deleteOne']['filter']);
184
+ const schema = model.schema;
185
+
186
+ _addDiscriminatorToObject(schema, op['deleteOne']['filter']);
187
+
188
+ try {
189
+ op['deleteOne']['filter'] = cast(model.schema,
190
+ op['deleteOne']['filter']);
191
+ } catch (error) {
192
+ return callback(error, null);
193
+ }
194
+
195
+ callback(null);
196
+ };
197
+ } else if (op['deleteMany']) {
198
+ return (callback) => {
199
+ const model = decideModelByObject(originalModel, op['deleteMany']['filter']);
200
+ const schema = model.schema;
201
+
202
+ _addDiscriminatorToObject(schema, op['deleteMany']['filter']);
203
+
204
+ try {
205
+ op['deleteMany']['filter'] = cast(model.schema,
206
+ op['deleteMany']['filter']);
207
+ } catch (error) {
208
+ return callback(error, null);
209
+ }
210
+
211
+ callback(null);
212
+ };
213
+ } else {
214
+ return (callback) => {
215
+ callback(new Error('Invalid op passed to `bulkWrite()`'), null);
216
+ };
217
+ }
218
+ };
219
+
220
+ function _addDiscriminatorToObject(schema, obj) {
221
+ if (schema == null) {
222
+ return;
223
+ }
224
+ if (schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) {
225
+ obj[schema.discriminatorMapping.key] = schema.discriminatorMapping.value;
226
+ }
227
+ }
228
+
229
+ /**
230
+ * gets discriminator model if discriminator key is present in object
231
+ * @api private
232
+ */
233
+
234
+ function decideModelByObject(model, object) {
235
+ const discriminatorKey = model.schema.options.discriminatorKey;
236
+ if (object != null && object.hasOwnProperty(discriminatorKey)) {
237
+ model = getDiscriminatorByValue(model.discriminators, object[discriminatorKey]) || model;
238
+ }
239
+ return model;
240
+ }
@@ -0,0 +1,218 @@
1
+ 'use strict';
2
+
3
+ const Mixed = require('../../schema/mixed');
4
+ const applyBuiltinPlugins = require('../schema/applyBuiltinPlugins');
5
+ const defineKey = require('../document/compile').defineKey;
6
+ const get = require('../get');
7
+ const utils = require('../../utils');
8
+ const mergeDiscriminatorSchema = require('../../helpers/discriminator/mergeDiscriminatorSchema');
9
+
10
+ const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = {
11
+ toJSON: true,
12
+ toObject: true,
13
+ _id: true,
14
+ id: true,
15
+ virtuals: true,
16
+ methods: true
17
+ };
18
+
19
+ /*!
20
+ * ignore
21
+ */
22
+
23
+ module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins, mergeHooks) {
24
+ if (!(schema && schema.instanceOfSchema)) {
25
+ throw new Error('You must pass a valid discriminator Schema');
26
+ }
27
+
28
+ mergeHooks = mergeHooks == null ? true : mergeHooks;
29
+
30
+ if (model.schema.discriminatorMapping &&
31
+ !model.schema.discriminatorMapping.isRoot) {
32
+ throw new Error('Discriminator "' + name +
33
+ '" can only be a discriminator of the root model');
34
+ }
35
+
36
+ if (applyPlugins) {
37
+ const applyPluginsToDiscriminators = get(model.base,
38
+ 'options.applyPluginsToDiscriminators', false) || !mergeHooks;
39
+ // Even if `applyPluginsToDiscriminators` isn't set, we should still apply
40
+ // global plugins to schemas embedded in the discriminator schema (gh-7370)
41
+ model.base._applyPlugins(schema, {
42
+ skipTopLevel: !applyPluginsToDiscriminators
43
+ });
44
+ } else if (!mergeHooks) {
45
+ applyBuiltinPlugins(schema);
46
+ }
47
+
48
+ const key = model.schema.options.discriminatorKey;
49
+
50
+ const existingPath = model.schema.path(key);
51
+ if (existingPath != null) {
52
+ if (!utils.hasUserDefinedProperty(existingPath.options, 'select')) {
53
+ existingPath.options.select = true;
54
+ }
55
+ existingPath.options.$skipDiscriminatorCheck = true;
56
+ } else {
57
+ const baseSchemaAddition = {};
58
+ baseSchemaAddition[key] = {
59
+ default: void 0,
60
+ select: true,
61
+ $skipDiscriminatorCheck: true
62
+ };
63
+ baseSchemaAddition[key][model.schema.options.typeKey] = String;
64
+ model.schema.add(baseSchemaAddition);
65
+ defineKey({
66
+ prop: key,
67
+ prototype: model.prototype,
68
+ options: model.schema.options
69
+ });
70
+ }
71
+
72
+ if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) {
73
+ throw new Error('Discriminator "' + name +
74
+ '" cannot have field with name "' + key + '"');
75
+ }
76
+
77
+ let value = name;
78
+ if ((typeof tiedValue === 'string' && tiedValue.length) || tiedValue != null) {
79
+ value = tiedValue;
80
+ }
81
+
82
+ function merge(schema, baseSchema) {
83
+ // Retain original schema before merging base schema
84
+ schema._baseSchema = baseSchema;
85
+ if (baseSchema.paths._id &&
86
+ baseSchema.paths._id.options &&
87
+ !baseSchema.paths._id.options.auto) {
88
+ schema.remove('_id');
89
+ }
90
+
91
+ // Find conflicting paths: if something is a path in the base schema
92
+ // and a nested path in the child schema, overwrite the base schema path.
93
+ // See gh-6076
94
+ const baseSchemaPaths = Object.keys(baseSchema.paths);
95
+ const conflictingPaths = [];
96
+
97
+ for (const path of baseSchemaPaths) {
98
+ if (schema.nested[path]) {
99
+ conflictingPaths.push(path);
100
+ continue;
101
+ }
102
+
103
+ if (path.indexOf('.') === -1) {
104
+ continue;
105
+ }
106
+ const sp = path.split('.').slice(0, -1);
107
+ let cur = '';
108
+ for (const piece of sp) {
109
+ cur += (cur.length ? '.' : '') + piece;
110
+ if (schema.paths[cur] instanceof Mixed ||
111
+ schema.singleNestedPaths[cur] instanceof Mixed) {
112
+ conflictingPaths.push(path);
113
+ }
114
+ }
115
+ }
116
+
117
+ mergeDiscriminatorSchema(schema, baseSchema, {
118
+ omit: { discriminators: true, base: true, _applyDiscriminators: true },
119
+ omitNested: conflictingPaths.reduce((cur, path) => {
120
+ cur['tree.' + path] = true;
121
+ return cur;
122
+ }, {})
123
+ });
124
+
125
+ // Clean up conflicting paths _after_ merging re: gh-6076
126
+ for (const conflictingPath of conflictingPaths) {
127
+ delete schema.paths[conflictingPath];
128
+ }
129
+
130
+ // Rebuild schema models because schemas may have been merged re: #7884
131
+ schema.childSchemas.forEach(obj => {
132
+ obj.model.prototype.$__setSchema(obj.schema);
133
+ });
134
+
135
+ const obj = {};
136
+ obj[key] = {
137
+ default: value,
138
+ select: true,
139
+ set: function(newName) {
140
+ if (newName === value || (Array.isArray(value) && utils.deepEqual(newName, value))) {
141
+ return value;
142
+ }
143
+ throw new Error('Can\'t set discriminator key "' + key + '"');
144
+ },
145
+ $skipDiscriminatorCheck: true
146
+ };
147
+ obj[key][schema.options.typeKey] = existingPath ? existingPath.options[schema.options.typeKey] : String;
148
+ schema.add(obj);
149
+
150
+ schema.discriminatorMapping = { key: key, value: value, isRoot: false };
151
+
152
+ if (baseSchema.options.collection) {
153
+ schema.options.collection = baseSchema.options.collection;
154
+ }
155
+
156
+ const toJSON = schema.options.toJSON;
157
+ const toObject = schema.options.toObject;
158
+ const _id = schema.options._id;
159
+ const id = schema.options.id;
160
+
161
+ const keys = Object.keys(schema.options);
162
+ schema.options.discriminatorKey = baseSchema.options.discriminatorKey;
163
+
164
+ for (const _key of keys) {
165
+ if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) {
166
+ // Special case: compiling a model sets `pluralization = true` by default. Avoid throwing an error
167
+ // for that case. See gh-9238
168
+ if (_key === 'pluralization' && schema.options[_key] == true && baseSchema.options[_key] == null) {
169
+ continue;
170
+ }
171
+
172
+ if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) {
173
+ throw new Error('Can\'t customize discriminator option ' + _key +
174
+ ' (can only modify ' +
175
+ Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') +
176
+ ')');
177
+ }
178
+ }
179
+ }
180
+ schema.options = utils.clone(baseSchema.options);
181
+ if (toJSON) schema.options.toJSON = toJSON;
182
+ if (toObject) schema.options.toObject = toObject;
183
+ if (typeof _id !== 'undefined') {
184
+ schema.options._id = _id;
185
+ }
186
+ schema.options.id = id;
187
+ if (mergeHooks) {
188
+ schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks);
189
+ }
190
+ if (applyPlugins) {
191
+ schema.plugins = Array.prototype.slice.call(baseSchema.plugins);
192
+ }
193
+ schema.callQueue = baseSchema.callQueue.concat(schema.callQueue);
194
+ delete schema._requiredpaths; // reset just in case Schema#requiredPaths() was called on either schema
195
+ }
196
+
197
+ // merges base schema into new discriminator schema and sets new type field.
198
+ merge(schema, model.schema);
199
+
200
+ if (!model.discriminators) {
201
+ model.discriminators = {};
202
+ }
203
+
204
+ if (!model.schema.discriminatorMapping) {
205
+ model.schema.discriminatorMapping = { key: key, value: null, isRoot: true };
206
+ }
207
+ if (!model.schema.discriminators) {
208
+ model.schema.discriminators = {};
209
+ }
210
+
211
+ model.schema.discriminators[name] = schema;
212
+
213
+ if (model.discriminators[name] && !schema.options.overwriteModels) {
214
+ throw new Error('Discriminator with name "' + name + '" already exists');
215
+ }
216
+
217
+ return schema;
218
+ };
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ module.exports = function pushNestedArrayPaths(paths, nestedArray, path) {
4
+ if (nestedArray == null) {
5
+ return;
6
+ }
7
+
8
+ for (let i = 0; i < nestedArray.length; ++i) {
9
+ if (Array.isArray(nestedArray[i])) {
10
+ pushNestedArrayPaths(paths, nestedArray[i], path + '.' + i);
11
+ } else {
12
+ paths.push(path + '.' + i);
13
+ }
14
+ }
15
+ };
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ module.exports = function once(fn) {
4
+ let called = false;
5
+ return function() {
6
+ if (called) {
7
+ return;
8
+ }
9
+ called = true;
10
+ return fn.apply(null, arguments);
11
+ };
12
+ };
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ module.exports = parallelLimit;
4
+
5
+ /*!
6
+ * ignore
7
+ */
8
+
9
+ function parallelLimit(fns, limit, callback) {
10
+ let numInProgress = 0;
11
+ let numFinished = 0;
12
+ let error = null;
13
+
14
+ if (limit <= 0) {
15
+ throw new Error('Limit must be positive');
16
+ }
17
+
18
+ if (fns.length === 0) {
19
+ return callback(null, []);
20
+ }
21
+
22
+ for (let i = 0; i < fns.length && i < limit; ++i) {
23
+ _start();
24
+ }
25
+
26
+ function _start() {
27
+ fns[numFinished + numInProgress](_done(numFinished + numInProgress));
28
+ ++numInProgress;
29
+ }
30
+
31
+ const results = [];
32
+
33
+ function _done(index) {
34
+ return (err, res) => {
35
+ --numInProgress;
36
+ ++numFinished;
37
+
38
+ if (error != null) {
39
+ return;
40
+ }
41
+ if (err != null) {
42
+ error = err;
43
+ return callback(error);
44
+ }
45
+
46
+ results[index] = res;
47
+
48
+ if (numFinished === fns.length) {
49
+ return callback(null, results);
50
+ } else if (numFinished + numInProgress < fns.length) {
51
+ _start();
52
+ }
53
+ };
54
+ }
55
+ }
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ const dotRE = /\./g;
4
+ module.exports = function parentPaths(path) {
5
+ if (path.indexOf('.') === -1) {
6
+ return [path];
7
+ }
8
+ const pieces = path.split(dotRE);
9
+ const len = pieces.length;
10
+ const ret = new Array(len);
11
+ let cur = '';
12
+ for (let i = 0; i < len; ++i) {
13
+ cur += (cur.length !== 0) ? '.' + pieces[i] : pieces[i];
14
+ ret[i] = cur;
15
+ }
16
+
17
+ return ret;
18
+ };
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ const specialProperties = require('../specialProperties');
4
+
5
+
6
+ module.exports = function setDottedPath(obj, path, val) {
7
+ if (path.indexOf('.') === -1) {
8
+ if (specialProperties.has(path)) {
9
+ return;
10
+ }
11
+
12
+ obj[path] = val;
13
+ return;
14
+ }
15
+ const parts = path.split('.');
16
+
17
+ const last = parts.pop();
18
+ let cur = obj;
19
+ for (const part of parts) {
20
+ if (specialProperties.has(part)) {
21
+ continue;
22
+ }
23
+ if (cur[part] == null) {
24
+ cur[part] = {};
25
+ }
26
+
27
+ cur = cur[part];
28
+ }
29
+
30
+ if (!specialProperties.has(last)) {
31
+ cur[last] = val;
32
+ }
33
+ };
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ module.exports = pluralize;
4
+
5
+ /**
6
+ * Pluralization rules.
7
+ */
8
+
9
+ exports.pluralization = [
10
+ [/(m)an$/gi, '$1en'],
11
+ [/(pe)rson$/gi, '$1ople'],
12
+ [/(child)$/gi, '$1ren'],
13
+ [/^(ox)$/gi, '$1en'],
14
+ [/(ax|test)is$/gi, '$1es'],
15
+ [/(octop|vir)us$/gi, '$1i'],
16
+ [/(alias|status)$/gi, '$1es'],
17
+ [/(bu)s$/gi, '$1ses'],
18
+ [/(buffal|tomat|potat)o$/gi, '$1oes'],
19
+ [/([ti])um$/gi, '$1a'],
20
+ [/sis$/gi, 'ses'],
21
+ [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],
22
+ [/(hive)$/gi, '$1s'],
23
+ [/([^aeiouy]|qu)y$/gi, '$1ies'],
24
+ [/(x|ch|ss|sh)$/gi, '$1es'],
25
+ [/(matr|vert|ind)ix|ex$/gi, '$1ices'],
26
+ [/([m|l])ouse$/gi, '$1ice'],
27
+ [/(kn|w|l)ife$/gi, '$1ives'],
28
+ [/(quiz)$/gi, '$1zes'],
29
+ [/^goose$/i, 'geese'],
30
+ [/s$/gi, 's'],
31
+ [/([^a-z])$/, '$1'],
32
+ [/$/gi, 's']
33
+ ];
34
+ const rules = exports.pluralization;
35
+
36
+ /**
37
+ * Uncountable words.
38
+ *
39
+ * These words are applied while processing the argument to `toCollectionName`.
40
+ * @api public
41
+ */
42
+
43
+ exports.uncountables = [
44
+ 'advice',
45
+ 'energy',
46
+ 'excretion',
47
+ 'digestion',
48
+ 'cooperation',
49
+ 'health',
50
+ 'justice',
51
+ 'labour',
52
+ 'machinery',
53
+ 'equipment',
54
+ 'information',
55
+ 'pollution',
56
+ 'sewage',
57
+ 'paper',
58
+ 'money',
59
+ 'species',
60
+ 'series',
61
+ 'rain',
62
+ 'rice',
63
+ 'fish',
64
+ 'sheep',
65
+ 'moose',
66
+ 'deer',
67
+ 'news',
68
+ 'expertise',
69
+ 'status',
70
+ 'media'
71
+ ];
72
+ const uncountables = exports.uncountables;
73
+
74
+ /**
75
+ * Pluralize function.
76
+ *
77
+ * @author TJ Holowaychuk (extracted from _ext.js_)
78
+ * @param {String} string to pluralize
79
+ * @api private
80
+ */
81
+
82
+ function pluralize(str) {
83
+ let found;
84
+ str = str.toLowerCase();
85
+ if (!~uncountables.indexOf(str)) {
86
+ found = rules.filter(function(rule) {
87
+ return str.match(rule[0]);
88
+ });
89
+ if (found[0]) {
90
+ return str.replace(found[0][0], found[0][1]);
91
+ }
92
+ }
93
+ return str;
94
+ }
@@ -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
+ };