@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,1164 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies
5
+ */
6
+
7
+ const AggregationCursor = require('./cursor/AggregationCursor');
8
+ const Query = require('./query');
9
+ const { applyGlobalMaxTimeMS, applyGlobalDiskUse } = require('./helpers/query/applyGlobalOption');
10
+ const getConstructorName = require('./helpers/getConstructorName');
11
+ const prepareDiscriminatorPipeline = require('./helpers/aggregate/prepareDiscriminatorPipeline');
12
+ const promiseOrCallback = require('./helpers/promiseOrCallback');
13
+ const stringifyFunctionOperators = require('./helpers/aggregate/stringifyFunctionOperators');
14
+ const utils = require('./utils');
15
+ const read = Query.prototype.read;
16
+ const readConcern = Query.prototype.readConcern;
17
+
18
+ const validRedactStringValues = new Set(['$$DESCEND', '$$PRUNE', '$$KEEP']);
19
+
20
+ /**
21
+ * Aggregate constructor used for building aggregation pipelines. Do not
22
+ * instantiate this class directly, use [Model.aggregate()](/docs/api/model.html#model_Model-aggregate) instead.
23
+ *
24
+ * #### Example:
25
+ *
26
+ * const aggregate = Model.aggregate([
27
+ * { $project: { a: 1, b: 1 } },
28
+ * { $skip: 5 }
29
+ * ]);
30
+ *
31
+ * Model.
32
+ * aggregate([{ $match: { age: { $gte: 21 }}}]).
33
+ * unwind('tags').
34
+ * exec(callback);
35
+ *
36
+ * #### Note:
37
+ *
38
+ * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
39
+ * - Mongoose does **not** cast pipeline stages. The below will **not** work unless `_id` is a string in the database
40
+ *
41
+ * new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
42
+ * // Do this instead to cast to an ObjectId
43
+ * new Aggregate([{ $match: { _id: new mongoose.Types.ObjectId('00000000000000000000000a') } }]);
44
+ *
45
+ * @see MongoDB https://www.mongodb.com/docs/manual/applications/aggregation/
46
+ * @see driver https://mongodb.github.io/node-mongodb-native/4.9/classes/Collection.html#aggregate
47
+ * @param {Array} [pipeline] aggregation pipeline as an array of objects
48
+ * @param {Model} [model] the model to use with this aggregate.
49
+ * @api public
50
+ */
51
+
52
+ function Aggregate(pipeline, model) {
53
+ this._pipeline = [];
54
+ this._model = model;
55
+ this.options = {};
56
+
57
+ if (arguments.length === 1 && Array.isArray(pipeline)) {
58
+ this.append.apply(this, pipeline);
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Contains options passed down to the [aggregate command](https://www.mongodb.com/docs/manual/reference/command/aggregate/).
64
+ * Supported options are:
65
+ *
66
+ * - [`allowDiskUse`](#aggregate_Aggregate-allowDiskUse)
67
+ * - `bypassDocumentValidation`
68
+ * - [`collation`](#aggregate_Aggregate-collation)
69
+ * - `comment`
70
+ * - [`cursor`](#aggregate_Aggregate-cursor)
71
+ * - [`explain`](#aggregate_Aggregate-explain)
72
+ * - `fieldsAsRaw`
73
+ * - [`hint`](#aggregate_Aggregate-hint)
74
+ * - `let`
75
+ * - `maxTimeMS`
76
+ * - `raw`
77
+ * - [`readConcern`](#aggregate_Aggregate-readConcern)
78
+ * - `readPreference`
79
+ * - [`session`](#aggregate_Aggregate-session)
80
+ * - `writeConcern`
81
+ *
82
+ * @property options
83
+ * @memberOf Aggregate
84
+ * @api public
85
+ */
86
+
87
+ Aggregate.prototype.options;
88
+
89
+ /**
90
+ * Get/set the model that this aggregation will execute on.
91
+ *
92
+ * #### Example:
93
+ *
94
+ * const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]);
95
+ * aggregate.model() === MyModel; // true
96
+ *
97
+ * // Change the model. There's rarely any reason to do this.
98
+ * aggregate.model(SomeOtherModel);
99
+ * aggregate.model() === SomeOtherModel; // true
100
+ *
101
+ * @param {Model} [model] Set the model associated with this aggregate. If not provided, returns the already stored model.
102
+ * @return {Model}
103
+ * @api public
104
+ */
105
+
106
+ Aggregate.prototype.model = function(model) {
107
+ if (arguments.length === 0) {
108
+ return this._model;
109
+ }
110
+
111
+ this._model = model;
112
+ if (model.schema != null) {
113
+ if (this.options.readPreference == null &&
114
+ model.schema.options.read != null) {
115
+ this.options.readPreference = model.schema.options.read;
116
+ }
117
+ if (this.options.collation == null &&
118
+ model.schema.options.collation != null) {
119
+ this.options.collation = model.schema.options.collation;
120
+ }
121
+ }
122
+
123
+ return model;
124
+ };
125
+
126
+ /**
127
+ * Appends new operators to this aggregate pipeline
128
+ *
129
+ * #### Example:
130
+ *
131
+ * aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
132
+ *
133
+ * // or pass an array
134
+ * const pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
135
+ * aggregate.append(pipeline);
136
+ *
137
+ * @param {...Object|Object[]} ops operator(s) to append. Can either be a spread of objects or a single parameter of a object array.
138
+ * @return {Aggregate}
139
+ * @api public
140
+ */
141
+
142
+ Aggregate.prototype.append = function() {
143
+ const args = (arguments.length === 1 && Array.isArray(arguments[0]))
144
+ ? arguments[0]
145
+ : [...arguments];
146
+
147
+ if (!args.every(isOperator)) {
148
+ throw new Error('Arguments must be aggregate pipeline operators');
149
+ }
150
+
151
+ this._pipeline = this._pipeline.concat(args);
152
+
153
+ return this;
154
+ };
155
+
156
+ /**
157
+ * Appends a new $addFields operator to this aggregate pipeline.
158
+ * Requires MongoDB v3.4+ to work
159
+ *
160
+ * #### Example:
161
+ *
162
+ * // adding new fields based on existing fields
163
+ * aggregate.addFields({
164
+ * newField: '$b.nested'
165
+ * , plusTen: { $add: ['$val', 10]}
166
+ * , sub: {
167
+ * name: '$a'
168
+ * }
169
+ * })
170
+ *
171
+ * // etc
172
+ * aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });
173
+ *
174
+ * @param {Object} arg field specification
175
+ * @see $addFields https://www.mongodb.com/docs/manual/reference/operator/aggregation/addFields/
176
+ * @return {Aggregate}
177
+ * @api public
178
+ */
179
+ Aggregate.prototype.addFields = function(arg) {
180
+ if (typeof arg !== 'object' || arg === null || Array.isArray(arg)) {
181
+ throw new Error('Invalid addFields() argument. Must be an object');
182
+ }
183
+ return this.append({ $addFields: Object.assign({}, arg) });
184
+ };
185
+
186
+ /**
187
+ * Appends a new $project operator to this aggregate pipeline.
188
+ *
189
+ * Mongoose query [selection syntax](#query_Query-select) is also supported.
190
+ *
191
+ * #### Example:
192
+ *
193
+ * // include a, include b, exclude _id
194
+ * aggregate.project("a b -_id");
195
+ *
196
+ * // or you may use object notation, useful when
197
+ * // you have keys already prefixed with a "-"
198
+ * aggregate.project({a: 1, b: 1, _id: 0});
199
+ *
200
+ * // reshaping documents
201
+ * aggregate.project({
202
+ * newField: '$b.nested'
203
+ * , plusTen: { $add: ['$val', 10]}
204
+ * , sub: {
205
+ * name: '$a'
206
+ * }
207
+ * })
208
+ *
209
+ * // etc
210
+ * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
211
+ *
212
+ * @param {Object|String} arg field specification
213
+ * @see projection https://www.mongodb.com/docs/manual/reference/aggregation/project/
214
+ * @return {Aggregate}
215
+ * @api public
216
+ */
217
+
218
+ Aggregate.prototype.project = function(arg) {
219
+ const fields = {};
220
+
221
+ if (typeof arg === 'object' && !Array.isArray(arg)) {
222
+ Object.keys(arg).forEach(function(field) {
223
+ fields[field] = arg[field];
224
+ });
225
+ } else if (arguments.length === 1 && typeof arg === 'string') {
226
+ arg.split(/\s+/).forEach(function(field) {
227
+ if (!field) {
228
+ return;
229
+ }
230
+ const include = field[0] === '-' ? 0 : 1;
231
+ if (include === 0) {
232
+ field = field.substring(1);
233
+ }
234
+ fields[field] = include;
235
+ });
236
+ } else {
237
+ throw new Error('Invalid project() argument. Must be string or object');
238
+ }
239
+
240
+ return this.append({ $project: fields });
241
+ };
242
+
243
+ /**
244
+ * Appends a new custom $group operator to this aggregate pipeline.
245
+ *
246
+ * #### Example:
247
+ *
248
+ * aggregate.group({ _id: "$department" });
249
+ *
250
+ * @see $group https://www.mongodb.com/docs/manual/reference/aggregation/group/
251
+ * @method group
252
+ * @memberOf Aggregate
253
+ * @instance
254
+ * @param {Object} arg $group operator contents
255
+ * @return {Aggregate}
256
+ * @api public
257
+ */
258
+
259
+ /**
260
+ * Appends a new custom $match operator to this aggregate pipeline.
261
+ *
262
+ * #### Example:
263
+ *
264
+ * aggregate.match({ department: { $in: [ "sales", "engineering" ] } });
265
+ *
266
+ * @see $match https://www.mongodb.com/docs/manual/reference/aggregation/match/
267
+ * @method match
268
+ * @memberOf Aggregate
269
+ * @instance
270
+ * @param {Object} arg $match operator contents
271
+ * @return {Aggregate}
272
+ * @api public
273
+ */
274
+
275
+ /**
276
+ * Appends a new $skip operator to this aggregate pipeline.
277
+ *
278
+ * #### Example:
279
+ *
280
+ * aggregate.skip(10);
281
+ *
282
+ * @see $skip https://www.mongodb.com/docs/manual/reference/aggregation/skip/
283
+ * @method skip
284
+ * @memberOf Aggregate
285
+ * @instance
286
+ * @param {Number} num number of records to skip before next stage
287
+ * @return {Aggregate}
288
+ * @api public
289
+ */
290
+
291
+ /**
292
+ * Appends a new $limit operator to this aggregate pipeline.
293
+ *
294
+ * #### Example:
295
+ *
296
+ * aggregate.limit(10);
297
+ *
298
+ * @see $limit https://www.mongodb.com/docs/manual/reference/aggregation/limit/
299
+ * @method limit
300
+ * @memberOf Aggregate
301
+ * @instance
302
+ * @param {Number} num maximum number of records to pass to the next stage
303
+ * @return {Aggregate}
304
+ * @api public
305
+ */
306
+
307
+
308
+ /**
309
+ * Appends a new $densify operator to this aggregate pipeline.
310
+ *
311
+ * #### Example:
312
+ *
313
+ * aggregate.densify({
314
+ * field: 'timestamp',
315
+ * range: {
316
+ * step: 1,
317
+ * unit: 'hour',
318
+ * bounds: [new Date('2021-05-18T00:00:00.000Z'), new Date('2021-05-18T08:00:00.000Z')]
319
+ * }
320
+ * });
321
+ *
322
+ * @see $densify https://www.mongodb.com/docs/manual/reference/operator/aggregation/densify/
323
+ * @method densify
324
+ * @memberOf Aggregate
325
+ * @instance
326
+ * @param {Object} arg $densify operator contents
327
+ * @return {Aggregate}
328
+ * @api public
329
+ */
330
+
331
+ /**
332
+ * Appends a new $fill operator to this aggregate pipeline.
333
+ *
334
+ * #### Example:
335
+ *
336
+ * aggregate.fill({
337
+ * output: {
338
+ * bootsSold: { value: 0 },
339
+ * sandalsSold: { value: 0 },
340
+ * sneakersSold: { value: 0 }
341
+ * }
342
+ * });
343
+ *
344
+ * @see $fill https://www.mongodb.com/docs/manual/reference/operator/aggregation/fill/
345
+ * @method fill
346
+ * @memberOf Aggregate
347
+ * @instance
348
+ * @param {Object} arg $fill operator contents
349
+ * @return {Aggregate}
350
+ * @api public
351
+ */
352
+
353
+ /**
354
+ * Appends a new $geoNear operator to this aggregate pipeline.
355
+ *
356
+ * #### Note:
357
+ *
358
+ * **MUST** be used as the first operator in the pipeline.
359
+ *
360
+ * #### Example:
361
+ *
362
+ * aggregate.near({
363
+ * near: { type: 'Point', coordinates: [40.724, -73.997] },
364
+ * distanceField: "dist.calculated", // required
365
+ * maxDistance: 0.008,
366
+ * query: { type: "public" },
367
+ * includeLocs: "dist.location",
368
+ * spherical: true,
369
+ * });
370
+ *
371
+ * @see $geoNear https://www.mongodb.com/docs/manual/reference/aggregation/geoNear/
372
+ * @method near
373
+ * @memberOf Aggregate
374
+ * @instance
375
+ * @param {Object} arg
376
+ * @return {Aggregate}
377
+ * @api public
378
+ */
379
+
380
+ Aggregate.prototype.near = function(arg) {
381
+ const op = {};
382
+ op.$geoNear = arg;
383
+ return this.append(op);
384
+ };
385
+
386
+ /*!
387
+ * define methods
388
+ */
389
+
390
+ 'group match skip limit out densify fill'.split(' ').forEach(function($operator) {
391
+ Aggregate.prototype[$operator] = function(arg) {
392
+ const op = {};
393
+ op['$' + $operator] = arg;
394
+ return this.append(op);
395
+ };
396
+ });
397
+
398
+ /**
399
+ * Appends new custom $unwind operator(s) to this aggregate pipeline.
400
+ *
401
+ * Note that the `$unwind` operator requires the path name to start with '$'.
402
+ * Mongoose will prepend '$' if the specified field doesn't start '$'.
403
+ *
404
+ * #### Example:
405
+ *
406
+ * aggregate.unwind("tags");
407
+ * aggregate.unwind("a", "b", "c");
408
+ * aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true });
409
+ *
410
+ * @see $unwind https://www.mongodb.com/docs/manual/reference/aggregation/unwind/
411
+ * @param {String|Object|String[]|Object[]} fields the field(s) to unwind, either as field names or as [objects with options](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind/#document-operand-with-options). If passing a string, prefixing the field name with '$' is optional. If passing an object, `path` must start with '$'.
412
+ * @return {Aggregate}
413
+ * @api public
414
+ */
415
+
416
+ Aggregate.prototype.unwind = function() {
417
+ const args = [...arguments];
418
+
419
+ const res = [];
420
+ for (const arg of args) {
421
+ if (arg && typeof arg === 'object') {
422
+ res.push({ $unwind: arg });
423
+ } else if (typeof arg === 'string') {
424
+ res.push({
425
+ $unwind: (arg[0] === '$') ? arg : '$' + arg
426
+ });
427
+ } else {
428
+ throw new Error('Invalid arg "' + arg + '" to unwind(), ' +
429
+ 'must be string or object');
430
+ }
431
+ }
432
+
433
+ return this.append.apply(this, res);
434
+ };
435
+
436
+ /**
437
+ * Appends a new $replaceRoot operator to this aggregate pipeline.
438
+ *
439
+ * Note that the `$replaceRoot` operator requires field strings to start with '$'.
440
+ * If you are passing in a string Mongoose will prepend '$' if the specified field doesn't start '$'.
441
+ * If you are passing in an object the strings in your expression will not be altered.
442
+ *
443
+ * #### Example:
444
+ *
445
+ * aggregate.replaceRoot("user");
446
+ *
447
+ * aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } });
448
+ *
449
+ * @see $replaceRoot https://www.mongodb.com/docs/manual/reference/operator/aggregation/replaceRoot
450
+ * @param {String|Object} newRoot the field or document which will become the new root document
451
+ * @return {Aggregate}
452
+ * @api public
453
+ */
454
+
455
+ Aggregate.prototype.replaceRoot = function(newRoot) {
456
+ let ret;
457
+
458
+ if (typeof newRoot === 'string') {
459
+ ret = newRoot.startsWith('$') ? newRoot : '$' + newRoot;
460
+ } else {
461
+ ret = newRoot;
462
+ }
463
+
464
+ return this.append({
465
+ $replaceRoot: {
466
+ newRoot: ret
467
+ }
468
+ });
469
+ };
470
+
471
+ /**
472
+ * Appends a new $count operator to this aggregate pipeline.
473
+ *
474
+ * #### Example:
475
+ *
476
+ * aggregate.count("userCount");
477
+ *
478
+ * @see $count https://www.mongodb.com/docs/manual/reference/operator/aggregation/count
479
+ * @param {String} fieldName The name of the output field which has the count as its value. It must be a non-empty string, must not start with $ and must not contain the . character.
480
+ * @return {Aggregate}
481
+ * @api public
482
+ */
483
+
484
+ Aggregate.prototype.count = function(fieldName) {
485
+ return this.append({ $count: fieldName });
486
+ };
487
+
488
+ /**
489
+ * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name
490
+ * or a pipeline object.
491
+ *
492
+ * Note that the `$sortByCount` operator requires the new root to start with '$'.
493
+ * Mongoose will prepend '$' if the specified field name doesn't start with '$'.
494
+ *
495
+ * #### Example:
496
+ *
497
+ * aggregate.sortByCount('users');
498
+ * aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })
499
+ *
500
+ * @see $sortByCount https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount/
501
+ * @param {Object|String} arg
502
+ * @return {Aggregate} this
503
+ * @api public
504
+ */
505
+
506
+ Aggregate.prototype.sortByCount = function(arg) {
507
+ if (arg && typeof arg === 'object') {
508
+ return this.append({ $sortByCount: arg });
509
+ } else if (typeof arg === 'string') {
510
+ return this.append({
511
+ $sortByCount: (arg[0] === '$') ? arg : '$' + arg
512
+ });
513
+ } else {
514
+ throw new TypeError('Invalid arg "' + arg + '" to sortByCount(), ' +
515
+ 'must be string or object');
516
+ }
517
+ };
518
+
519
+ /**
520
+ * Appends new custom $lookup operator to this aggregate pipeline.
521
+ *
522
+ * #### Example:
523
+ *
524
+ * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });
525
+ *
526
+ * @see $lookup https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/#pipe._S_lookup
527
+ * @param {Object} options to $lookup as described in the above link
528
+ * @return {Aggregate}
529
+ * @api public
530
+ */
531
+
532
+ Aggregate.prototype.lookup = function(options) {
533
+ return this.append({ $lookup: options });
534
+ };
535
+
536
+ /**
537
+ * Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection.
538
+ *
539
+ * Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if `{ allowDiskUse: true }` is specified.
540
+ *
541
+ * #### Example:
542
+ *
543
+ * // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }`
544
+ * aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites
545
+ *
546
+ * @see $graphLookup https://www.mongodb.com/docs/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup
547
+ * @param {Object} options to $graphLookup as described in the above link
548
+ * @return {Aggregate}
549
+ * @api public
550
+ */
551
+
552
+ Aggregate.prototype.graphLookup = function(options) {
553
+ const cloneOptions = {};
554
+ if (options) {
555
+ if (!utils.isObject(options)) {
556
+ throw new TypeError('Invalid graphLookup() argument. Must be an object.');
557
+ }
558
+
559
+ utils.mergeClone(cloneOptions, options);
560
+ const startWith = cloneOptions.startWith;
561
+
562
+ if (startWith && typeof startWith === 'string') {
563
+ cloneOptions.startWith = cloneOptions.startWith.startsWith('$') ?
564
+ cloneOptions.startWith :
565
+ '$' + cloneOptions.startWith;
566
+ }
567
+
568
+ }
569
+ return this.append({ $graphLookup: cloneOptions });
570
+ };
571
+
572
+ /**
573
+ * Appends new custom $sample operator to this aggregate pipeline.
574
+ *
575
+ * #### Example:
576
+ *
577
+ * aggregate.sample(3); // Add a pipeline that picks 3 random documents
578
+ *
579
+ * @see $sample https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/#pipe._S_sample
580
+ * @param {Number} size number of random documents to pick
581
+ * @return {Aggregate}
582
+ * @api public
583
+ */
584
+
585
+ Aggregate.prototype.sample = function(size) {
586
+ return this.append({ $sample: { size: size } });
587
+ };
588
+
589
+ /**
590
+ * Appends a new $sort operator to this aggregate pipeline.
591
+ *
592
+ * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
593
+ *
594
+ * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
595
+ *
596
+ * #### Example:
597
+ *
598
+ * // these are equivalent
599
+ * aggregate.sort({ field: 'asc', test: -1 });
600
+ * aggregate.sort('field -test');
601
+ *
602
+ * @see $sort https://www.mongodb.com/docs/manual/reference/aggregation/sort/
603
+ * @param {Object|String} arg
604
+ * @return {Aggregate} this
605
+ * @api public
606
+ */
607
+
608
+ Aggregate.prototype.sort = function(arg) {
609
+ // TODO refactor to reuse the query builder logic
610
+
611
+ const sort = {};
612
+
613
+ if (getConstructorName(arg) === 'Object') {
614
+ const desc = ['desc', 'descending', -1];
615
+ Object.keys(arg).forEach(function(field) {
616
+ // If sorting by text score, skip coercing into 1/-1
617
+ if (arg[field] instanceof Object && arg[field].$meta) {
618
+ sort[field] = arg[field];
619
+ return;
620
+ }
621
+ sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
622
+ });
623
+ } else if (arguments.length === 1 && typeof arg === 'string') {
624
+ arg.split(/\s+/).forEach(function(field) {
625
+ if (!field) {
626
+ return;
627
+ }
628
+ const ascend = field[0] === '-' ? -1 : 1;
629
+ if (ascend === -1) {
630
+ field = field.substring(1);
631
+ }
632
+ sort[field] = ascend;
633
+ });
634
+ } else {
635
+ throw new TypeError('Invalid sort() argument. Must be a string or object.');
636
+ }
637
+
638
+ return this.append({ $sort: sort });
639
+ };
640
+
641
+ /**
642
+ * Appends new $unionWith operator to this aggregate pipeline.
643
+ *
644
+ * #### Example:
645
+ *
646
+ * aggregate.unionWith({ coll: 'users', pipeline: [ { $match: { _id: 1 } } ] });
647
+ *
648
+ * @see $unionWith https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionWith
649
+ * @param {Object} options to $unionWith query as described in the above link
650
+ * @return {Aggregate}
651
+ * @api public
652
+ */
653
+
654
+ Aggregate.prototype.unionWith = function(options) {
655
+ return this.append({ $unionWith: options });
656
+ };
657
+
658
+
659
+ /**
660
+ * Sets the readPreference option for the aggregation query.
661
+ *
662
+ * #### Example:
663
+ *
664
+ * await Model.aggregate(pipeline).read('primaryPreferred');
665
+ *
666
+ * @param {String|ReadPreference} pref one of the listed preference options or their aliases
667
+ * @param {Array} [tags] optional tags for this query. DEPRECATED
668
+ * @return {Aggregate} this
669
+ * @api public
670
+ * @see mongodb https://www.mongodb.com/docs/manual/applications/replication/#read-preference
671
+ */
672
+
673
+ Aggregate.prototype.read = function(pref, tags) {
674
+ read.call(this, pref, tags);
675
+ return this;
676
+ };
677
+
678
+ /**
679
+ * Sets the readConcern level for the aggregation query.
680
+ *
681
+ * #### Example:
682
+ *
683
+ * await Model.aggregate(pipeline).readConcern('majority');
684
+ *
685
+ * @param {String} level one of the listed read concern level or their aliases
686
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/read-concern/
687
+ * @return {Aggregate} this
688
+ * @api public
689
+ */
690
+
691
+ Aggregate.prototype.readConcern = function(level) {
692
+ readConcern.call(this, level);
693
+ return this;
694
+ };
695
+
696
+ /**
697
+ * Appends a new $redact operator to this aggregate pipeline.
698
+ *
699
+ * If 3 arguments are supplied, Mongoose will wrap them with if-then-else of $cond operator respectively
700
+ * If `thenExpr` or `elseExpr` is string, make sure it starts with $$, like `$$DESCEND`, `$$PRUNE` or `$$KEEP`.
701
+ *
702
+ * #### Example:
703
+ *
704
+ * await Model.aggregate(pipeline).redact({
705
+ * $cond: {
706
+ * if: { $eq: [ '$level', 5 ] },
707
+ * then: '$$PRUNE',
708
+ * else: '$$DESCEND'
709
+ * }
710
+ * });
711
+ *
712
+ * // $redact often comes with $cond operator, you can also use the following syntax provided by mongoose
713
+ * await Model.aggregate(pipeline).redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND');
714
+ *
715
+ * @param {Object} expression redact options or conditional expression
716
+ * @param {String|Object} [thenExpr] true case for the condition
717
+ * @param {String|Object} [elseExpr] false case for the condition
718
+ * @return {Aggregate} this
719
+ * @see $redact https://www.mongodb.com/docs/manual/reference/operator/aggregation/redact/
720
+ * @api public
721
+ */
722
+
723
+ Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) {
724
+ if (arguments.length === 3) {
725
+ if ((typeof thenExpr === 'string' && !validRedactStringValues.has(thenExpr)) ||
726
+ (typeof elseExpr === 'string' && !validRedactStringValues.has(elseExpr))) {
727
+ throw new Error('If thenExpr or elseExpr is string, it must be either $$DESCEND, $$PRUNE or $$KEEP');
728
+ }
729
+
730
+ expression = {
731
+ $cond: {
732
+ if: expression,
733
+ then: thenExpr,
734
+ else: elseExpr
735
+ }
736
+ };
737
+ } else if (arguments.length !== 1) {
738
+ throw new TypeError('Invalid arguments');
739
+ }
740
+
741
+ return this.append({ $redact: expression });
742
+ };
743
+
744
+ /**
745
+ * Execute the aggregation with explain
746
+ *
747
+ * #### Example:
748
+ *
749
+ * Model.aggregate(..).explain(callback)
750
+ *
751
+ * @param {String} [verbosity]
752
+ * @param {Function} [callback] The callback function to call, if not specified, will return a Promise instead.
753
+ * @return {Promise} Returns a promise if no "callback" is given
754
+ */
755
+
756
+ Aggregate.prototype.explain = function(verbosity, callback) {
757
+ const model = this._model;
758
+ if (typeof verbosity === 'function') {
759
+ callback = verbosity;
760
+ verbosity = null;
761
+ }
762
+
763
+ return promiseOrCallback(callback, cb => {
764
+ if (!this._pipeline.length) {
765
+ const err = new Error('Aggregate has empty pipeline');
766
+ return cb(err);
767
+ }
768
+
769
+ prepareDiscriminatorPipeline(this._pipeline, this._model.schema);
770
+
771
+ model.hooks.execPre('aggregate', this, error => {
772
+ if (error) {
773
+ const _opts = { error: error };
774
+ return model.hooks.execPost('aggregate', this, [null], _opts, error => {
775
+ cb(error);
776
+ });
777
+ }
778
+
779
+ model.collection.aggregate(this._pipeline, this.options, (error, cursor) => {
780
+ if (error != null) {
781
+ const _opts = { error: error };
782
+ return model.hooks.execPost('aggregate', this, [null], _opts, error => {
783
+ cb(error);
784
+ });
785
+ }
786
+ if (verbosity != null) {
787
+ cursor.explain(verbosity, (error, result) => {
788
+ const _opts = { error: error };
789
+ return model.hooks.execPost('aggregate', this, [result], _opts, error => {
790
+ if (error) {
791
+ return cb(error);
792
+ }
793
+ return cb(null, result);
794
+ });
795
+ });
796
+ } else {
797
+ cursor.explain((error, result) => {
798
+ const _opts = { error: error };
799
+ return model.hooks.execPost('aggregate', this, [result], _opts, error => {
800
+ if (error) {
801
+ return cb(error);
802
+ }
803
+ return cb(null, result);
804
+ });
805
+ });
806
+ }
807
+ });
808
+ });
809
+ }, model.events);
810
+ };
811
+
812
+ /**
813
+ * Sets the allowDiskUse option for the aggregation query
814
+ *
815
+ * #### Example:
816
+ *
817
+ * await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true);
818
+ *
819
+ * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation.
820
+ * @return {Aggregate} this
821
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/command/aggregate/
822
+ */
823
+
824
+ Aggregate.prototype.allowDiskUse = function(value) {
825
+ this.options.allowDiskUse = value;
826
+ return this;
827
+ };
828
+
829
+ /**
830
+ * Sets the hint option for the aggregation query
831
+ *
832
+ * #### Example:
833
+ *
834
+ * Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback)
835
+ *
836
+ * @param {Object|String} value a hint object or the index name
837
+ * @return {Aggregate} this
838
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/command/aggregate/
839
+ */
840
+
841
+ Aggregate.prototype.hint = function(value) {
842
+ this.options.hint = value;
843
+ return this;
844
+ };
845
+
846
+ /**
847
+ * Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html).
848
+ *
849
+ * #### Example:
850
+ *
851
+ * const session = await Model.startSession();
852
+ * await Model.aggregate(..).session(session);
853
+ *
854
+ * @param {ClientSession} session
855
+ * @return {Aggregate} this
856
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/command/aggregate/
857
+ */
858
+
859
+ Aggregate.prototype.session = function(session) {
860
+ if (session == null) {
861
+ delete this.options.session;
862
+ } else {
863
+ this.options.session = session;
864
+ }
865
+ return this;
866
+ };
867
+
868
+ /**
869
+ * Lets you set arbitrary options, for middleware or plugins.
870
+ *
871
+ * #### Example:
872
+ *
873
+ * const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
874
+ * agg.options; // `{ allowDiskUse: true }`
875
+ *
876
+ * @param {Object} options keys to merge into current options
877
+ * @param {Number} [options.maxTimeMS] number limits the time this aggregation will run, see [MongoDB docs on `maxTimeMS`](https://www.mongodb.com/docs/manual/reference/operator/meta/maxTimeMS/)
878
+ * @param {Boolean} [options.allowDiskUse] boolean if true, the MongoDB server will use the hard drive to store data during this aggregation
879
+ * @param {Object} [options.collation] object see [`Aggregate.prototype.collation()`](#aggregate_Aggregate-collation)
880
+ * @param {ClientSession} [options.session] ClientSession see [`Aggregate.prototype.session()`](#aggregate_Aggregate-session)
881
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/command/aggregate/
882
+ * @return {Aggregate} this
883
+ * @api public
884
+ */
885
+
886
+ Aggregate.prototype.option = function(value) {
887
+ for (const key in value) {
888
+ this.options[key] = value[key];
889
+ }
890
+ return this;
891
+ };
892
+
893
+ /**
894
+ * Sets the `cursor` option and executes this aggregation, returning an aggregation cursor.
895
+ * Cursors are useful if you want to process the results of the aggregation one-at-a-time
896
+ * because the aggregation result is too big to fit into memory.
897
+ *
898
+ * #### Example:
899
+ *
900
+ * const cursor = Model.aggregate(..).cursor({ batchSize: 1000 });
901
+ * cursor.eachAsync(function(doc, i) {
902
+ * // use doc
903
+ * });
904
+ *
905
+ * @param {Object} options
906
+ * @param {Number} [options.batchSize] set the cursor batch size
907
+ * @param {Boolean} [options.useMongooseAggCursor] use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics)
908
+ * @return {AggregationCursor} cursor representing this aggregation
909
+ * @api public
910
+ * @see mongodb https://mongodb.github.io/node-mongodb-native/4.9/classes/AggregationCursor.html
911
+ */
912
+
913
+ Aggregate.prototype.cursor = function(options) {
914
+ this.options.cursor = options || {};
915
+ return new AggregationCursor(this); // return this;
916
+ };
917
+
918
+ /**
919
+ * Adds a collation
920
+ *
921
+ * #### Example:
922
+ *
923
+ * const res = await Model.aggregate(pipeline).collation({ locale: 'en_US', strength: 1 });
924
+ *
925
+ * @param {Object} collation options
926
+ * @return {Aggregate} this
927
+ * @api public
928
+ * @see mongodb https://mongodb.github.io/node-mongodb-native/4.9/interfaces/CollationOptions.html
929
+ */
930
+
931
+ Aggregate.prototype.collation = function(collation) {
932
+ this.options.collation = collation;
933
+ return this;
934
+ };
935
+
936
+ /**
937
+ * Combines multiple aggregation pipelines.
938
+ *
939
+ * #### Example:
940
+ *
941
+ * const res = await Model.aggregate().facet({
942
+ * books: [{ groupBy: '$author' }],
943
+ * price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }]
944
+ * });
945
+ *
946
+ * // Output: { books: [...], price: [{...}, {...}] }
947
+ *
948
+ * @param {Object} facet options
949
+ * @return {Aggregate} this
950
+ * @see $facet https://www.mongodb.com/docs/manual/reference/operator/aggregation/facet/
951
+ * @api public
952
+ */
953
+
954
+ Aggregate.prototype.facet = function(options) {
955
+ return this.append({ $facet: options });
956
+ };
957
+
958
+ /**
959
+ * Helper for [Atlas Text Search](https://www.mongodb.com/docs/atlas/atlas-search/tutorial/)'s
960
+ * `$search` stage.
961
+ *
962
+ * #### Example:
963
+ *
964
+ * const res = await Model.aggregate().
965
+ * search({
966
+ * text: {
967
+ * query: 'baseball',
968
+ * path: 'plot'
969
+ * }
970
+ * });
971
+ *
972
+ * // Output: [{ plot: '...', title: '...' }]
973
+ *
974
+ * @param {Object} $search options
975
+ * @return {Aggregate} this
976
+ * @see $search https://www.mongodb.com/docs/atlas/atlas-search/tutorial/
977
+ * @api public
978
+ */
979
+
980
+ Aggregate.prototype.search = function(options) {
981
+ return this.append({ $search: options });
982
+ };
983
+
984
+ /**
985
+ * Returns the current pipeline
986
+ *
987
+ * #### Example:
988
+ *
989
+ * MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }]
990
+ *
991
+ * @return {Array} The current pipeline similar to the operation that will be executed
992
+ * @api public
993
+ */
994
+
995
+ Aggregate.prototype.pipeline = function() {
996
+ return this._pipeline;
997
+ };
998
+
999
+ /**
1000
+ * Executes the aggregate pipeline on the currently bound Model.
1001
+ *
1002
+ * #### Example:
1003
+ *
1004
+ * aggregate.exec(callback);
1005
+ *
1006
+ * // Because a promise is returned, the `callback` is optional.
1007
+ * const result = await aggregate.exec();
1008
+ *
1009
+ * @param {Function} [callback]
1010
+ * @return {Promise} Returns a Promise if no "callback" is given.
1011
+ * @api public
1012
+ */
1013
+
1014
+ Aggregate.prototype.exec = function(callback) {
1015
+ if (!this._model) {
1016
+ throw new Error('Aggregate not bound to any Model');
1017
+ }
1018
+ const model = this._model;
1019
+ const collection = this._model.collection;
1020
+
1021
+ applyGlobalMaxTimeMS(this.options, model);
1022
+ applyGlobalDiskUse(this.options, model);
1023
+
1024
+ if (this.options && this.options.cursor) {
1025
+ return new AggregationCursor(this);
1026
+ }
1027
+
1028
+ return promiseOrCallback(callback, cb => {
1029
+ prepareDiscriminatorPipeline(this._pipeline, this._model.schema);
1030
+ stringifyFunctionOperators(this._pipeline);
1031
+
1032
+ model.hooks.execPre('aggregate', this, error => {
1033
+ if (error) {
1034
+ const _opts = { error: error };
1035
+ return model.hooks.execPost('aggregate', this, [null], _opts, error => {
1036
+ cb(error);
1037
+ });
1038
+ }
1039
+ if (!this._pipeline.length) {
1040
+ return cb(new Error('Aggregate has empty pipeline'));
1041
+ }
1042
+
1043
+ const options = utils.clone(this.options || {});
1044
+
1045
+ collection.aggregate(this._pipeline, options, (err, cursor) => {
1046
+ if (err != null) {
1047
+ return cb(err);
1048
+ }
1049
+
1050
+ cursor.toArray((error, result) => {
1051
+ const _opts = { error: error };
1052
+ model.hooks.execPost('aggregate', this, [result], _opts, (error, result) => {
1053
+ if (error) {
1054
+ return cb(error);
1055
+ }
1056
+
1057
+ cb(null, result);
1058
+ });
1059
+ });
1060
+ });
1061
+ });
1062
+ }, model.events);
1063
+ };
1064
+
1065
+ /**
1066
+ * Provides a Promise-like `then` function, which will call `.exec` without a callback
1067
+ * Compatible with `await`.
1068
+ *
1069
+ * #### Example:
1070
+ *
1071
+ * Model.aggregate(..).then(successCallback, errorCallback);
1072
+ *
1073
+ * @param {Function} [resolve] successCallback
1074
+ * @param {Function} [reject] errorCallback
1075
+ * @return {Promise}
1076
+ */
1077
+ Aggregate.prototype.then = function(resolve, reject) {
1078
+ return this.exec().then(resolve, reject);
1079
+ };
1080
+
1081
+ /**
1082
+ * Executes the query returning a `Promise` which will be
1083
+ * resolved with either the doc(s) or rejected with the error.
1084
+ * Like [`.then()`](#query_Query-then), but only takes a rejection handler.
1085
+ * Compatible with `await`.
1086
+ *
1087
+ * @param {Function} [reject]
1088
+ * @return {Promise}
1089
+ * @api public
1090
+ */
1091
+
1092
+ Aggregate.prototype.catch = function(reject) {
1093
+ return this.exec().then(null, reject);
1094
+ };
1095
+
1096
+ /**
1097
+ * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js)
1098
+ * You do not need to call this function explicitly, the JavaScript runtime
1099
+ * will call it for you.
1100
+ *
1101
+ * #### Example:
1102
+ *
1103
+ * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
1104
+ * for await (const doc of agg) {
1105
+ * console.log(doc.name);
1106
+ * }
1107
+ *
1108
+ * Node.js 10.x supports async iterators natively without any flags. You can
1109
+ * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187).
1110
+ *
1111
+ * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If
1112
+ * `Symbol.asyncIterator` is undefined, that means your Node.js version does not
1113
+ * support async iterators.
1114
+ *
1115
+ * @method [Symbol.asyncIterator]
1116
+ * @memberOf Aggregate
1117
+ * @instance
1118
+ * @api public
1119
+ */
1120
+
1121
+ if (Symbol.asyncIterator != null) {
1122
+ Aggregate.prototype[Symbol.asyncIterator] = function() {
1123
+ return this.cursor({ useMongooseAggCursor: true }).transformNull()._transformForAsyncIterator();
1124
+ };
1125
+ }
1126
+
1127
+ /*!
1128
+ * Helpers
1129
+ */
1130
+
1131
+ /**
1132
+ * Checks whether an object is likely a pipeline operator
1133
+ *
1134
+ * @param {Object} obj object to check
1135
+ * @return {Boolean}
1136
+ * @api private
1137
+ */
1138
+
1139
+ function isOperator(obj) {
1140
+ if (typeof obj !== 'object' || obj === null) {
1141
+ return false;
1142
+ }
1143
+
1144
+ const k = Object.keys(obj);
1145
+
1146
+ return k.length === 1 && k[0][0] === '$';
1147
+ }
1148
+
1149
+ /**
1150
+ * Adds the appropriate `$match` pipeline step to the top of an aggregate's
1151
+ * pipeline, should it's model is a non-root discriminator type. This is
1152
+ * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`.
1153
+ *
1154
+ * @param {Aggregate} aggregate Aggregate to prepare
1155
+ * @api private
1156
+ */
1157
+
1158
+ Aggregate._prepareDiscriminatorPipeline = prepareDiscriminatorPipeline;
1159
+
1160
+ /*!
1161
+ * Exports
1162
+ */
1163
+
1164
+ module.exports = Aggregate;