@datanimbus/mongoose 9.13.1 → 9.13.2

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 (302) hide show
  1. package/README.md +80 -70
  2. package/eslint.config.mjs +202 -0
  3. package/index.js +2 -1
  4. package/lib/aggregate.js +276 -174
  5. package/lib/cast/bigint.js +46 -0
  6. package/lib/cast/boolean.js +3 -3
  7. package/lib/cast/decimal128.js +4 -1
  8. package/lib/cast/double.js +56 -0
  9. package/lib/cast/int32.js +42 -0
  10. package/lib/cast/number.js +6 -6
  11. package/lib/cast/objectid.js +3 -3
  12. package/lib/cast/string.js +3 -3
  13. package/lib/cast/uuid.js +35 -0
  14. package/lib/cast.js +100 -92
  15. package/lib/collection.js +31 -22
  16. package/lib/connection.js +792 -507
  17. package/lib/constants.js +73 -0
  18. package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
  19. package/lib/cursor/changeStream.js +218 -0
  20. package/lib/cursor/queryCursor.js +676 -0
  21. package/lib/defaults/schemaDefaultsCache.js +62 -0
  22. package/lib/document.js +2419 -1306
  23. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  24. package/lib/drivers/node-mongodb-native/collection.js +101 -135
  25. package/lib/drivers/node-mongodb-native/connection.js +386 -28
  26. package/lib/drivers/node-mongodb-native/index.js +3 -5
  27. package/lib/error/browserMissingSchema.js +5 -4
  28. package/lib/error/bulkSaveIncompleteError.js +44 -0
  29. package/lib/error/cast.js +30 -21
  30. package/lib/error/createCollectionsError.js +26 -0
  31. package/lib/error/divergentArray.js +11 -9
  32. package/lib/error/eachAsyncMultiError.js +2 -2
  33. package/lib/error/index.js +38 -29
  34. package/lib/error/invalidSchemaOption.js +32 -0
  35. package/lib/error/messages.js +4 -3
  36. package/lib/error/missingSchema.js +8 -6
  37. package/lib/error/notFound.js +7 -5
  38. package/lib/error/objectExpected.js +9 -8
  39. package/lib/error/objectParameter.js +12 -11
  40. package/lib/error/overwriteModel.js +7 -6
  41. package/lib/error/parallelSave.js +11 -8
  42. package/lib/error/parallelValidate.js +9 -7
  43. package/lib/error/serverSelection.js +1 -0
  44. package/lib/error/setOptionError.js +11 -9
  45. package/lib/error/strict.js +12 -10
  46. package/lib/error/strictPopulate.js +11 -9
  47. package/lib/error/syncIndexes.js +2 -2
  48. package/lib/error/validation.js +11 -17
  49. package/lib/error/validator.js +9 -8
  50. package/lib/error/version.js +12 -10
  51. package/lib/filters/operators.js +8 -0
  52. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
  53. package/lib/helpers/buildMiddlewareFilter.js +42 -0
  54. package/lib/helpers/clone.js +121 -35
  55. package/lib/helpers/common.js +7 -7
  56. package/lib/helpers/cursor/eachAsync.js +14 -11
  57. package/lib/helpers/cursor/waitForInitialization.js +17 -0
  58. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  59. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
  60. package/lib/helpers/discriminator/getConstructor.js +9 -6
  61. package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
  62. package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
  63. package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
  64. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
  65. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
  66. package/lib/helpers/document/applyDefaults.js +82 -14
  67. package/lib/helpers/document/applyTimestamps.js +106 -0
  68. package/lib/helpers/document/applyVirtuals.js +147 -0
  69. package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
  70. package/lib/helpers/document/compile.js +20 -15
  71. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  72. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
  73. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  74. package/lib/helpers/document/isInPathsToSave.js +24 -0
  75. package/lib/helpers/document/toObjectRecursive.js +49 -0
  76. package/lib/helpers/get.js +1 -1
  77. package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
  78. package/lib/helpers/getInheritedProperty.js +28 -0
  79. package/lib/helpers/getOwnProperty.js +19 -0
  80. package/lib/helpers/indexes/applySchemaCollation.js +1 -1
  81. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
  82. package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
  83. package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
  84. package/lib/helpers/indexes/isIndexEqual.js +13 -12
  85. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  86. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  87. package/lib/helpers/isBsonType.js +3 -6
  88. package/lib/helpers/isMongooseDocument.js +24 -0
  89. package/lib/helpers/isMongooseObject.js +6 -4
  90. package/lib/helpers/isObject.js +2 -2
  91. package/lib/helpers/isPOJO.js +12 -0
  92. package/lib/helpers/isSimpleValidator.js +2 -2
  93. package/lib/helpers/minimize.js +41 -0
  94. package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
  95. package/lib/helpers/model/applyHooks.js +72 -54
  96. package/lib/helpers/model/applyMethods.js +3 -3
  97. package/lib/helpers/model/applyStaticHooks.js +20 -50
  98. package/lib/helpers/model/castBulkWrite.js +278 -172
  99. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  100. package/lib/helpers/model/discriminator.js +77 -21
  101. package/lib/helpers/omitUndefined.js +20 -0
  102. package/lib/helpers/parallelLimit.js +61 -34
  103. package/lib/helpers/path/setDottedPath.js +1 -1
  104. package/lib/helpers/pathTrie.js +167 -0
  105. package/lib/helpers/pluralize.js +5 -4
  106. package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
  107. package/lib/helpers/populate/assignVals.js +46 -21
  108. package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
  109. package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
  110. package/lib/helpers/populate/getSchemaTypes.js +27 -30
  111. package/lib/helpers/populate/getVirtual.js +31 -0
  112. package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
  113. package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
  114. package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
  115. package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
  116. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  117. package/lib/helpers/populate/splitPopulateQuery.js +81 -0
  118. package/lib/helpers/printJestWarning.js +1 -1
  119. package/lib/helpers/processConnectionOptions.js +7 -2
  120. package/lib/helpers/projection/applyProjection.js +8 -2
  121. package/lib/helpers/projection/hasIncludedChildren.js +1 -1
  122. package/lib/helpers/projection/isExclusive.js +8 -6
  123. package/lib/helpers/projection/isInclusive.js +2 -1
  124. package/lib/helpers/projection/isPathExcluded.js +3 -3
  125. package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
  126. package/lib/helpers/projection/isSubpath.js +1 -1
  127. package/lib/helpers/projection/parseProjection.js +9 -4
  128. package/lib/helpers/query/applyGlobalOption.js +9 -9
  129. package/lib/helpers/query/cast$expr.js +52 -23
  130. package/lib/helpers/query/castFilterPath.js +22 -22
  131. package/lib/helpers/query/castUpdate.js +207 -79
  132. package/lib/helpers/query/cloneMongooseOptions.js +44 -0
  133. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
  134. package/lib/helpers/query/handleImmutable.js +18 -2
  135. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  136. package/lib/helpers/query/sanitizeFilter.js +3 -2
  137. package/lib/helpers/query/selectPopulatedFields.js +13 -0
  138. package/lib/helpers/query/validOps.js +1 -22
  139. package/lib/helpers/schema/applyPlugins.js +2 -2
  140. package/lib/helpers/schema/applyReadConcern.js +20 -0
  141. package/lib/helpers/schema/applyWriteConcern.js +12 -3
  142. package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
  143. package/lib/helpers/schema/getIndexes.js +20 -13
  144. package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
  145. package/lib/helpers/schema/getPath.js +11 -3
  146. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  147. package/lib/helpers/schema/handleIdOption.js +1 -1
  148. package/lib/helpers/schema/idGetter.js +7 -2
  149. package/lib/helpers/schema/merge.js +9 -1
  150. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  151. package/lib/helpers/schematype/handleImmutable.js +1 -1
  152. package/lib/helpers/setDefaultsOnInsert.js +85 -43
  153. package/lib/helpers/symbols.js +4 -4
  154. package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
  155. package/lib/helpers/timestamps/setupTimestamps.js +69 -37
  156. package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
  157. package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
  158. package/lib/helpers/update/castArrayFilters.js +68 -29
  159. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  160. package/lib/helpers/update/modifiedPaths.js +2 -2
  161. package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
  162. package/lib/helpers/updateValidators.js +87 -128
  163. package/lib/index.js +6 -1320
  164. package/lib/internal.js +7 -1
  165. package/lib/model.js +2587 -2618
  166. package/lib/modifiedPathsSnapshot.js +9 -0
  167. package/lib/mongoose.js +1456 -0
  168. package/lib/options/saveOptions.js +2 -0
  169. package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
  170. package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
  171. package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
  172. package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
  173. package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
  174. package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
  175. package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
  176. package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
  177. package/lib/options/schemaSubdocumentOptions.js +89 -0
  178. package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
  179. package/lib/options/schemaUnionOptions.js +32 -0
  180. package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
  181. package/lib/options.js +4 -1
  182. package/lib/plugins/index.js +0 -2
  183. package/lib/plugins/saveSubdocs.js +85 -50
  184. package/lib/plugins/sharding.js +43 -15
  185. package/lib/plugins/trackTransaction.js +46 -34
  186. package/lib/query.js +1844 -1909
  187. package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
  188. package/lib/schema/array.js +229 -169
  189. package/lib/schema/bigint.js +281 -0
  190. package/lib/schema/boolean.js +90 -26
  191. package/lib/schema/buffer.js +119 -50
  192. package/lib/schema/date.js +102 -38
  193. package/lib/schema/decimal128.js +88 -37
  194. package/lib/schema/{documentarray.js → documentArray.js} +259 -151
  195. package/lib/schema/documentArrayElement.js +180 -0
  196. package/lib/schema/double.js +244 -0
  197. package/lib/schema/index.js +12 -19
  198. package/lib/schema/int32.js +288 -0
  199. package/lib/schema/map.js +129 -20
  200. package/lib/schema/mixed.js +40 -26
  201. package/lib/schema/number.js +128 -51
  202. package/lib/schema/{objectid.js → objectId.js} +89 -47
  203. package/lib/schema/operators/exists.js +1 -1
  204. package/lib/schema/operators/geospatial.js +2 -2
  205. package/lib/schema/operators/text.js +4 -4
  206. package/lib/schema/string.js +125 -66
  207. package/lib/schema/subdocument.js +443 -0
  208. package/lib/schema/symbols.js +2 -0
  209. package/lib/schema/union.js +167 -0
  210. package/lib/schema/uuid.js +90 -120
  211. package/lib/schema.js +1267 -388
  212. package/lib/{schematype.js → schemaType.js} +481 -246
  213. package/lib/standardSchema/convertErrorToIssues.js +20 -0
  214. package/lib/{statemachine.js → stateMachine.js} +66 -17
  215. package/lib/tracing.js +38 -0
  216. package/lib/types/array/index.js +13 -10
  217. package/lib/types/array/methods/index.js +243 -63
  218. package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
  219. package/lib/types/buffer.js +31 -14
  220. package/lib/types/decimal128.js +1 -1
  221. package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
  222. package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
  223. package/lib/types/double.js +13 -0
  224. package/lib/types/index.js +5 -2
  225. package/lib/types/map.js +62 -25
  226. package/lib/types/objectid.js +2 -2
  227. package/lib/types/subdocument.js +79 -58
  228. package/lib/types/uuid.js +13 -0
  229. package/lib/utils.js +201 -155
  230. package/lib/{validoptions.js → validOptions.js} +10 -2
  231. package/lib/{virtualtype.js → virtualType.js} +47 -18
  232. package/package.json +75 -92
  233. package/types/aggregate.d.ts +31 -7
  234. package/types/augmentations.d.ts +2 -2
  235. package/types/collection.d.ts +21 -16
  236. package/types/connection.d.ts +82 -27
  237. package/types/cursor.d.ts +15 -10
  238. package/types/document.d.ts +137 -56
  239. package/types/error.d.ts +11 -6
  240. package/types/expressions.d.ts +33 -2
  241. package/types/index.d.ts +805 -190
  242. package/types/indexes.d.ts +85 -13
  243. package/types/inferhydrateddoctype.d.ts +151 -0
  244. package/types/inferrawdoctype.d.ts +201 -0
  245. package/types/inferschematype.d.ts +287 -128
  246. package/types/middlewares.d.ts +50 -7
  247. package/types/models.d.ts +1555 -268
  248. package/types/mongooseoptions.d.ts +56 -7
  249. package/types/pipelinestage.d.ts +42 -3
  250. package/types/populate.d.ts +63 -1
  251. package/types/query.d.ts +592 -255
  252. package/types/schemaoptions.d.ts +78 -12
  253. package/types/schematypes.d.ts +254 -65
  254. package/types/session.d.ts +0 -4
  255. package/types/tracing.d.ts +10 -0
  256. package/types/types.d.ts +25 -8
  257. package/types/utility.d.ts +329 -30
  258. package/types/validation.d.ts +19 -14
  259. package/types/virtuals.d.ts +10 -10
  260. package/.eslintrc.js +0 -232
  261. package/.mocharc.yml +0 -4
  262. package/browser.js +0 -8
  263. package/lgtm.yml +0 -12
  264. package/lib/browser.js +0 -158
  265. package/lib/browserDocument.js +0 -101
  266. package/lib/cursor/ChangeStream.js +0 -154
  267. package/lib/cursor/QueryCursor.js +0 -545
  268. package/lib/document_provider.js +0 -30
  269. package/lib/drivers/browser/ReadPreference.js +0 -7
  270. package/lib/drivers/browser/binary.js +0 -14
  271. package/lib/drivers/browser/decimal128.js +0 -7
  272. package/lib/drivers/browser/index.js +0 -16
  273. package/lib/drivers/browser/objectid.js +0 -29
  274. package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
  275. package/lib/drivers/node-mongodb-native/binary.js +0 -10
  276. package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
  277. package/lib/drivers/node-mongodb-native/objectid.js +0 -16
  278. package/lib/error/disconnected.js +0 -33
  279. package/lib/helpers/printStrictQueryWarning.js +0 -11
  280. package/lib/helpers/promiseOrCallback.js +0 -55
  281. package/lib/helpers/query/applyQueryMiddleware.js +0 -79
  282. package/lib/helpers/query/completeMany.js +0 -52
  283. package/lib/helpers/query/wrapThunk.js +0 -36
  284. package/lib/options/SchemaSubdocumentOptions.js +0 -42
  285. package/lib/options/removeOptions.js +0 -14
  286. package/lib/plugins/removeSubdocs.js +0 -31
  287. package/lib/plugins/validateBeforeSave.js +0 -45
  288. package/lib/promise_provider.js +0 -49
  289. package/lib/schema/DocumentArrayElement.js +0 -100
  290. package/lib/schema/SubdocumentPath.js +0 -369
  291. package/scripts/build-browser.js +0 -18
  292. package/scripts/create-tarball.js +0 -7
  293. package/scripts/generateSearch.js +0 -154
  294. package/scripts/tsc-diagnostics-check.js +0 -15
  295. package/tools/auth.js +0 -31
  296. package/tools/repl.js +0 -35
  297. package/tools/sharded.js +0 -46
  298. package/tsconfig.json +0 -9
  299. /package/lib/{connectionstate.js → connectionState.js} +0 -0
  300. /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
  301. /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
  302. /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
package/lib/aggregate.js CHANGED
@@ -4,14 +4,19 @@
4
4
  * Module dependencies
5
5
  */
6
6
 
7
- const AggregationCursor = require('./cursor/AggregationCursor');
7
+ const AggregationCursor = require('./cursor/aggregationCursor');
8
+ const MongooseError = require('./error/mongooseError');
8
9
  const Query = require('./query');
9
10
  const { applyGlobalMaxTimeMS, applyGlobalDiskUse } = require('./helpers/query/applyGlobalOption');
11
+ const clone = require('./helpers/clone');
10
12
  const getConstructorName = require('./helpers/getConstructorName');
11
13
  const prepareDiscriminatorPipeline = require('./helpers/aggregate/prepareDiscriminatorPipeline');
12
- const promiseOrCallback = require('./helpers/promiseOrCallback');
14
+ const { buildMiddlewareFilter } = require('./helpers/buildMiddlewareFilter');
13
15
  const stringifyFunctionOperators = require('./helpers/aggregate/stringifyFunctionOperators');
14
16
  const utils = require('./utils');
17
+ const { modelSymbol } = require('./helpers/symbols');
18
+ const { createTracedChannel } = require('./tracing');
19
+ const { trace: traceAggregate } = createTracedChannel('mongoose:aggregate');
15
20
  const read = Query.prototype.read;
16
21
  const readConcern = Query.prototype.readConcern;
17
22
 
@@ -19,7 +24,7 @@ const validRedactStringValues = new Set(['$$DESCEND', '$$PRUNE', '$$KEEP']);
19
24
 
20
25
  /**
21
26
  * 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.
27
+ * instantiate this class directly, use [Model.aggregate()](https://mongoosejs.com/docs/api/model.html#Model.aggregate()) instead.
23
28
  *
24
29
  * #### Example:
25
30
  *
@@ -31,7 +36,7 @@ const validRedactStringValues = new Set(['$$DESCEND', '$$PRUNE', '$$KEEP']);
31
36
  * Model.
32
37
  * aggregate([{ $match: { age: { $gte: 21 }}}]).
33
38
  * unwind('tags').
34
- * exec(callback);
39
+ * exec();
35
40
  *
36
41
  * #### Note:
37
42
  *
@@ -43,15 +48,19 @@ const validRedactStringValues = new Set(['$$DESCEND', '$$PRUNE', '$$KEEP']);
43
48
  * new Aggregate([{ $match: { _id: new mongoose.Types.ObjectId('00000000000000000000000a') } }]);
44
49
  *
45
50
  * @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
51
+ * @see driver https://mongodb.github.io/node-mongodb-native/7.0/classes/Collection.html#aggregate
47
52
  * @param {Array} [pipeline] aggregation pipeline as an array of objects
48
- * @param {Model} [model] the model to use with this aggregate.
53
+ * @param {Model|Connection} [modelOrConn] the model or connection to use with this aggregate.
49
54
  * @api public
50
55
  */
51
56
 
52
- function Aggregate(pipeline, model) {
57
+ function Aggregate(pipeline, modelOrConn) {
53
58
  this._pipeline = [];
54
- this._model = model;
59
+ if (modelOrConn == null || modelOrConn[modelSymbol]) {
60
+ this._model = modelOrConn;
61
+ } else {
62
+ this._connection = modelOrConn;
63
+ }
55
64
  this.options = {};
56
65
 
57
66
  if (arguments.length === 1 && Array.isArray(pipeline)) {
@@ -63,20 +72,20 @@ function Aggregate(pipeline, model) {
63
72
  * Contains options passed down to the [aggregate command](https://www.mongodb.com/docs/manual/reference/command/aggregate/).
64
73
  * Supported options are:
65
74
  *
66
- * - [`allowDiskUse`](#aggregate_Aggregate-allowDiskUse)
75
+ * - [`allowDiskUse`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.allowDiskUse())
67
76
  * - `bypassDocumentValidation`
68
- * - [`collation`](#aggregate_Aggregate-collation)
77
+ * - [`collation`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.collation())
69
78
  * - `comment`
70
- * - [`cursor`](#aggregate_Aggregate-cursor)
71
- * - [`explain`](#aggregate_Aggregate-explain)
79
+ * - [`cursor`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.cursor())
80
+ * - [`explain`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.explain())
72
81
  * - `fieldsAsRaw`
73
- * - [`hint`](#aggregate_Aggregate-hint)
82
+ * - [`hint`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.hint())
74
83
  * - `let`
75
84
  * - `maxTimeMS`
76
85
  * - `raw`
77
- * - [`readConcern`](#aggregate_Aggregate-readConcern)
86
+ * - [`readConcern`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.readConcern())
78
87
  * - `readPreference`
79
- * - [`session`](#aggregate_Aggregate-session)
88
+ * - [`session`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.session())
80
89
  * - `writeConcern`
81
90
  *
82
91
  * @property options
@@ -86,6 +95,24 @@ function Aggregate(pipeline, model) {
86
95
 
87
96
  Aggregate.prototype.options;
88
97
 
98
+ /**
99
+ * Returns default options for this aggregate.
100
+ *
101
+ * @param {Model} model
102
+ * @api private
103
+ */
104
+
105
+ Aggregate.prototype._optionsForExec = function() {
106
+ const options = this.options || {};
107
+
108
+ const asyncLocalStorage = this.model()?.db?.base.transactionAsyncLocalStorage?.getStore();
109
+ if (!Object.hasOwn(options, 'session') && asyncLocalStorage?.session != null) {
110
+ options.session = asyncLocalStorage.session;
111
+ }
112
+
113
+ return options;
114
+ };
115
+
89
116
  /**
90
117
  * Get/set the model that this aggregation will execute on.
91
118
  *
@@ -134,7 +161,7 @@ Aggregate.prototype.model = function(model) {
134
161
  * const pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
135
162
  * aggregate.append(pipeline);
136
163
  *
137
- * @param {...Object|Object[]} ops operator(s) to append. Can either be a spread of objects or a single parameter of a object array.
164
+ * @param {...object|object[]} ops operator(s) to append. Can either be a spread of objects or a single parameter of an object array.
138
165
  * @return {Aggregate}
139
166
  * @api public
140
167
  */
@@ -145,7 +172,7 @@ Aggregate.prototype.append = function() {
145
172
  : [...arguments];
146
173
 
147
174
  if (!args.every(isOperator)) {
148
- throw new Error('Arguments must be aggregate pipeline operators');
175
+ throw new MongooseError('Arguments must be aggregate pipeline operators');
149
176
  }
150
177
 
151
178
  this._pipeline = this._pipeline.concat(args);
@@ -155,7 +182,6 @@ Aggregate.prototype.append = function() {
155
182
 
156
183
  /**
157
184
  * Appends a new $addFields operator to this aggregate pipeline.
158
- * Requires MongoDB v3.4+ to work
159
185
  *
160
186
  * #### Example:
161
187
  *
@@ -171,14 +197,14 @@ Aggregate.prototype.append = function() {
171
197
  * // etc
172
198
  * aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });
173
199
  *
174
- * @param {Object} arg field specification
200
+ * @param {object} arg field specification
175
201
  * @see $addFields https://www.mongodb.com/docs/manual/reference/operator/aggregation/addFields/
176
202
  * @return {Aggregate}
177
203
  * @api public
178
204
  */
179
205
  Aggregate.prototype.addFields = function(arg) {
180
206
  if (typeof arg !== 'object' || arg === null || Array.isArray(arg)) {
181
- throw new Error('Invalid addFields() argument. Must be an object');
207
+ throw new MongooseError('Invalid addFields() argument. Must be an object');
182
208
  }
183
209
  return this.append({ $addFields: Object.assign({}, arg) });
184
210
  };
@@ -186,7 +212,7 @@ Aggregate.prototype.addFields = function(arg) {
186
212
  /**
187
213
  * Appends a new $project operator to this aggregate pipeline.
188
214
  *
189
- * Mongoose query [selection syntax](#query_Query-select) is also supported.
215
+ * Mongoose query [selection syntax](https://mongoosejs.com/docs/api/query.html#Query.prototype.select()) is also supported.
190
216
  *
191
217
  * #### Example:
192
218
  *
@@ -209,7 +235,7 @@ Aggregate.prototype.addFields = function(arg) {
209
235
  * // etc
210
236
  * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
211
237
  *
212
- * @param {Object|String} arg field specification
238
+ * @param {object|string} arg field specification
213
239
  * @see projection https://www.mongodb.com/docs/manual/reference/aggregation/project/
214
240
  * @return {Aggregate}
215
241
  * @api public
@@ -220,6 +246,10 @@ Aggregate.prototype.project = function(arg) {
220
246
 
221
247
  if (typeof arg === 'object' && !Array.isArray(arg)) {
222
248
  Object.keys(arg).forEach(function(field) {
249
+ // `fields[field] = ...` would set the prototype of `fields`
250
+ if (field === '__proto__') {
251
+ return;
252
+ }
223
253
  fields[field] = arg[field];
224
254
  });
225
255
  } else if (arguments.length === 1 && typeof arg === 'string') {
@@ -234,7 +264,7 @@ Aggregate.prototype.project = function(arg) {
234
264
  fields[field] = include;
235
265
  });
236
266
  } else {
237
- throw new Error('Invalid project() argument. Must be string or object');
267
+ throw new MongooseError('Invalid project() argument. Must be string or object');
238
268
  }
239
269
 
240
270
  return this.append({ $project: fields });
@@ -251,7 +281,7 @@ Aggregate.prototype.project = function(arg) {
251
281
  * @method group
252
282
  * @memberOf Aggregate
253
283
  * @instance
254
- * @param {Object} arg $group operator contents
284
+ * @param {object} arg $group operator contents
255
285
  * @return {Aggregate}
256
286
  * @api public
257
287
  */
@@ -267,7 +297,7 @@ Aggregate.prototype.project = function(arg) {
267
297
  * @method match
268
298
  * @memberOf Aggregate
269
299
  * @instance
270
- * @param {Object} arg $match operator contents
300
+ * @param {object} arg $match operator contents
271
301
  * @return {Aggregate}
272
302
  * @api public
273
303
  */
@@ -283,7 +313,7 @@ Aggregate.prototype.project = function(arg) {
283
313
  * @method skip
284
314
  * @memberOf Aggregate
285
315
  * @instance
286
- * @param {Number} num number of records to skip before next stage
316
+ * @param {number} num number of records to skip before next stage
287
317
  * @return {Aggregate}
288
318
  * @api public
289
319
  */
@@ -299,7 +329,7 @@ Aggregate.prototype.project = function(arg) {
299
329
  * @method limit
300
330
  * @memberOf Aggregate
301
331
  * @instance
302
- * @param {Number} num maximum number of records to pass to the next stage
332
+ * @param {number} num maximum number of records to pass to the next stage
303
333
  * @return {Aggregate}
304
334
  * @api public
305
335
  */
@@ -323,7 +353,7 @@ Aggregate.prototype.project = function(arg) {
323
353
  * @method densify
324
354
  * @memberOf Aggregate
325
355
  * @instance
326
- * @param {Object} arg $densify operator contents
356
+ * @param {object} arg $densify operator contents
327
357
  * @return {Aggregate}
328
358
  * @api public
329
359
  */
@@ -345,7 +375,7 @@ Aggregate.prototype.project = function(arg) {
345
375
  * @method fill
346
376
  * @memberOf Aggregate
347
377
  * @instance
348
- * @param {Object} arg $fill operator contents
378
+ * @param {object} arg $fill operator contents
349
379
  * @return {Aggregate}
350
380
  * @api public
351
381
  */
@@ -372,12 +402,24 @@ Aggregate.prototype.project = function(arg) {
372
402
  * @method near
373
403
  * @memberOf Aggregate
374
404
  * @instance
375
- * @param {Object} arg
405
+ * @param {object} arg
406
+ * @param {object|number[]} arg.near GeoJSON point or coordinates array
376
407
  * @return {Aggregate}
377
408
  * @api public
378
409
  */
379
410
 
380
411
  Aggregate.prototype.near = function(arg) {
412
+ if (arg == null) {
413
+ throw new MongooseError('Aggregate `near()` must be called with non-nullish argument');
414
+ }
415
+ if (arg.near == null) {
416
+ throw new MongooseError('Aggregate `near()` argument must have a `near` property');
417
+ }
418
+ const coordinates = Array.isArray(arg.near) ? arg.near : arg.near.coordinates;
419
+ if (typeof arg.near === 'object' && (!Array.isArray(coordinates) || coordinates.length < 2 || coordinates.find(c => typeof c !== 'number'))) {
420
+ throw new MongooseError(`Aggregate \`near()\` argument has invalid coordinates, got "${coordinates}"`);
421
+ }
422
+
381
423
  const op = {};
382
424
  op.$geoNear = arg;
383
425
  return this.append(op);
@@ -408,7 +450,7 @@ Aggregate.prototype.near = function(arg) {
408
450
  * aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true });
409
451
  *
410
452
  * @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 '$'.
453
+ * @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
454
  * @return {Aggregate}
413
455
  * @api public
414
456
  */
@@ -425,7 +467,7 @@ Aggregate.prototype.unwind = function() {
425
467
  $unwind: (arg[0] === '$') ? arg : '$' + arg
426
468
  });
427
469
  } else {
428
- throw new Error('Invalid arg "' + arg + '" to unwind(), ' +
470
+ throw new MongooseError('Invalid arg "' + arg + '" to unwind(), ' +
429
471
  'must be string or object');
430
472
  }
431
473
  }
@@ -447,7 +489,7 @@ Aggregate.prototype.unwind = function() {
447
489
  * aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } });
448
490
  *
449
491
  * @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
492
+ * @param {string|object} newRoot the field or document which will become the new root document
451
493
  * @return {Aggregate}
452
494
  * @api public
453
495
  */
@@ -476,7 +518,7 @@ Aggregate.prototype.replaceRoot = function(newRoot) {
476
518
  * aggregate.count("userCount");
477
519
  *
478
520
  * @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.
521
+ * @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
522
  * @return {Aggregate}
481
523
  * @api public
482
524
  */
@@ -498,7 +540,7 @@ Aggregate.prototype.count = function(fieldName) {
498
540
  * aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })
499
541
  *
500
542
  * @see $sortByCount https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortByCount/
501
- * @param {Object|String} arg
543
+ * @param {object|string} arg
502
544
  * @return {Aggregate} this
503
545
  * @api public
504
546
  */
@@ -524,7 +566,7 @@ Aggregate.prototype.sortByCount = function(arg) {
524
566
  * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });
525
567
  *
526
568
  * @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
569
+ * @param {object} options to $lookup as described in the above link
528
570
  * @return {Aggregate}
529
571
  * @api public
530
572
  */
@@ -544,7 +586,7 @@ Aggregate.prototype.lookup = function(options) {
544
586
  * 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
587
  *
546
588
  * @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
589
+ * @param {object} options to $graphLookup as described in the above link
548
590
  * @return {Aggregate}
549
591
  * @api public
550
592
  */
@@ -576,8 +618,11 @@ Aggregate.prototype.graphLookup = function(options) {
576
618
  *
577
619
  * aggregate.sample(3); // Add a pipeline that picks 3 random documents
578
620
  *
621
+ * // `$match` before `$sample` samples from the filtered subset
622
+ * aggregate.match({ difficulty: 'easy' }).sample(3);
623
+ *
579
624
  * @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
625
+ * @param {number} size number of random documents to pick
581
626
  * @return {Aggregate}
582
627
  * @api public
583
628
  */
@@ -600,7 +645,7 @@ Aggregate.prototype.sample = function(size) {
600
645
  * aggregate.sort('field -test');
601
646
  *
602
647
  * @see $sort https://www.mongodb.com/docs/manual/reference/aggregation/sort/
603
- * @param {Object|String} arg
648
+ * @param {object|string} arg
604
649
  * @return {Aggregate} this
605
650
  * @api public
606
651
  */
@@ -646,7 +691,7 @@ Aggregate.prototype.sort = function(arg) {
646
691
  * aggregate.unionWith({ coll: 'users', pipeline: [ { $match: { _id: 1 } } ] });
647
692
  *
648
693
  * @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
694
+ * @param {object} options to $unionWith query as described in the above link
650
695
  * @return {Aggregate}
651
696
  * @api public
652
697
  */
@@ -663,8 +708,8 @@ Aggregate.prototype.unionWith = function(options) {
663
708
  *
664
709
  * await Model.aggregate(pipeline).read('primaryPreferred');
665
710
  *
666
- * @param {String|ReadPreference} pref one of the listed preference options or their aliases
667
- * @param {Array} [tags] optional tags for this query. DEPRECATED
711
+ * @param {string|ReadPreference} pref one of the listed preference options or their aliases
712
+ * @param {Array} [tags] optional tags for this query.
668
713
  * @return {Aggregate} this
669
714
  * @api public
670
715
  * @see mongodb https://www.mongodb.com/docs/manual/applications/replication/#read-preference
@@ -682,7 +727,7 @@ Aggregate.prototype.read = function(pref, tags) {
682
727
  *
683
728
  * await Model.aggregate(pipeline).readConcern('majority');
684
729
  *
685
- * @param {String} level one of the listed read concern level or their aliases
730
+ * @param {'local'|'available'|'majority'|'snapshot'|'linearizable'|'l'|'a'|'m'|'s'|'lz'} level one of the listed read concern level or their aliases
686
731
  * @see mongodb https://www.mongodb.com/docs/manual/reference/read-concern/
687
732
  * @return {Aggregate} this
688
733
  * @api public
@@ -712,9 +757,9 @@ Aggregate.prototype.readConcern = function(level) {
712
757
  * // $redact often comes with $cond operator, you can also use the following syntax provided by mongoose
713
758
  * await Model.aggregate(pipeline).redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND');
714
759
  *
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
760
+ * @param {object} expression redact options or conditional expression
761
+ * @param {string|object} [thenExpr] true case for the condition
762
+ * @param {string|object} [elseExpr] false case for the condition
718
763
  * @return {Aggregate} this
719
764
  * @see $redact https://www.mongodb.com/docs/manual/reference/operator/aggregation/redact/
720
765
  * @api public
@@ -724,7 +769,7 @@ Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) {
724
769
  if (arguments.length === 3) {
725
770
  if ((typeof thenExpr === 'string' && !validRedactStringValues.has(thenExpr)) ||
726
771
  (typeof elseExpr === 'string' && !validRedactStringValues.has(elseExpr))) {
727
- throw new Error('If thenExpr or elseExpr is string, it must be either $$DESCEND, $$PRUNE or $$KEEP');
772
+ throw new MongooseError('If thenExpr or elseExpr is string, it must be either $$DESCEND, $$PRUNE or $$KEEP');
728
773
  }
729
774
 
730
775
  expression = {
@@ -746,67 +791,52 @@ Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) {
746
791
  *
747
792
  * #### Example:
748
793
  *
749
- * Model.aggregate(..).explain(callback)
794
+ * Model.aggregate(..).explain()
750
795
  *
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
796
+ * @param {'queryPlanner'|'executionStats'|'allPlansExecution'} [verbosity]
797
+ * @return {Promise}
754
798
  */
755
799
 
756
- Aggregate.prototype.explain = function(verbosity, callback) {
800
+ Aggregate.prototype.explain = async function explain(verbosity) {
801
+ if (typeof verbosity === 'function' || typeof arguments[1] === 'function') {
802
+ throw new MongooseError('Aggregate.prototype.explain() no longer accepts a callback');
803
+ }
757
804
  const model = this._model;
758
- if (typeof verbosity === 'function') {
759
- callback = verbosity;
760
- verbosity = null;
805
+
806
+ if (!this._pipeline.length) {
807
+ throw new MongooseError('Aggregate has empty pipeline');
761
808
  }
762
809
 
763
- return promiseOrCallback(callback, cb => {
764
- if (!this._pipeline.length) {
765
- const err = new Error('Aggregate has empty pipeline');
766
- return cb(err);
767
- }
810
+ prepareDiscriminatorPipeline(this._pipeline, this._model.schema);
768
811
 
769
- prepareDiscriminatorPipeline(this._pipeline, this._model.schema);
812
+ const preFilter = buildMiddlewareFilter(this.options, 'pre');
813
+ const postFilter = buildMiddlewareFilter(this.options, 'post');
770
814
 
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
- }
815
+ // Remove middleware option before passing to MongoDB
816
+ const { middleware, ...options } = this.options ?? {};
778
817
 
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);
818
+ try {
819
+ await model.hooks.execPre('aggregate', this, [], { filter: preFilter });
820
+ } catch (error) {
821
+ return await model.hooks.execPost('aggregate', this, [null], { error, filter: postFilter });
822
+ }
823
+
824
+ const cursor = await model.collection.aggregate(this._pipeline, options);
825
+
826
+ if (verbosity == null) {
827
+ verbosity = true;
828
+ }
829
+
830
+ let result = null;
831
+ try {
832
+ result = await cursor.explain(verbosity);
833
+ } catch (error) {
834
+ return await model.hooks.execPost('aggregate', this, [null], { error, filter: postFilter });
835
+ }
836
+
837
+ await model.hooks.execPost('aggregate', this, [result], { error: null, filter: postFilter });
838
+
839
+ return result;
810
840
  };
811
841
 
812
842
  /**
@@ -816,7 +846,7 @@ Aggregate.prototype.explain = function(verbosity, callback) {
816
846
  *
817
847
  * await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true);
818
848
  *
819
- * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation.
849
+ * @param {boolean} value Should tell server it can use hard drive to store data during aggregation.
820
850
  * @return {Aggregate} this
821
851
  * @see mongodb https://www.mongodb.com/docs/manual/reference/command/aggregate/
822
852
  */
@@ -831,9 +861,9 @@ Aggregate.prototype.allowDiskUse = function(value) {
831
861
  *
832
862
  * #### Example:
833
863
  *
834
- * Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback)
864
+ * Model.aggregate(..).hint({ qty: 1, category: 1 }).exec();
835
865
  *
836
- * @param {Object|String} value a hint object or the index name
866
+ * @param {object|string} value a hint object or the index name
837
867
  * @return {Aggregate} this
838
868
  * @see mongodb https://www.mongodb.com/docs/manual/reference/command/aggregate/
839
869
  */
@@ -844,7 +874,7 @@ Aggregate.prototype.hint = function(value) {
844
874
  };
845
875
 
846
876
  /**
847
- * Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html).
877
+ * Sets the session for this aggregation. Useful for [transactions](https://mongoosejs.com/docs/transactions.html).
848
878
  *
849
879
  * #### Example:
850
880
  *
@@ -873,11 +903,14 @@ Aggregate.prototype.session = function(session) {
873
903
  * const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
874
904
  * agg.options; // `{ allowDiskUse: true }`
875
905
  *
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)
906
+ * @param {object} options keys to merge into current options
907
+ * @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/)
908
+ * @param {boolean} [options.allowDiskUse] boolean if true, the MongoDB server will use the hard drive to store data during this aggregation
909
+ * @param {object} [options.collation] object see [`Aggregate.prototype.collation()`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.collation())
910
+ * @param {ClientSession} [options.session] ClientSession see [`Aggregate.prototype.session()`](https://mongoosejs.com/docs/api/aggregate.html#Aggregate.prototype.session())
911
+ * @param {boolean|object} [options.middleware=true] set to `false` to skip all user-defined middleware
912
+ * @param {boolean} [options.middleware.pre=true] set to `false` to skip only pre hooks
913
+ * @param {boolean} [options.middleware.post=true] set to `false` to skip only post hooks
881
914
  * @see mongodb https://www.mongodb.com/docs/manual/reference/command/aggregate/
882
915
  * @return {Aggregate} this
883
916
  * @api public
@@ -894,6 +927,8 @@ Aggregate.prototype.option = function(value) {
894
927
  * Sets the `cursor` option and executes this aggregation, returning an aggregation cursor.
895
928
  * Cursors are useful if you want to process the results of the aggregation one-at-a-time
896
929
  * because the aggregation result is too big to fit into memory.
930
+ * Creating an aggregation cursor runs pre aggregate hooks, but not post aggregate hooks.
931
+ * To skip pre aggregate hooks, pass `middleware: false` to `.cursor()`.
897
932
  *
898
933
  * #### Example:
899
934
  *
@@ -902,15 +937,23 @@ Aggregate.prototype.option = function(value) {
902
937
  * // use doc
903
938
  * });
904
939
  *
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)
940
+ * @param {object} options
941
+ * @param {number} [options.batchSize] set the cursor batch size
942
+ * @param {boolean|object} [options.middleware=true] set to `false` to skip user-defined pre aggregate middleware
943
+ * @param {boolean} [options.middleware.pre=true] set to `false` to skip pre aggregate middleware
944
+ * @param {boolean} [options.useMongooseAggCursor] use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics)
908
945
  * @return {AggregationCursor} cursor representing this aggregation
909
946
  * @api public
910
- * @see mongodb https://mongodb.github.io/node-mongodb-native/4.9/classes/AggregationCursor.html
947
+ * @see mongodb https://mongodb.github.io/node-mongodb-native/7.0/classes/AggregationCursor.html
911
948
  */
912
949
 
913
950
  Aggregate.prototype.cursor = function(options) {
951
+ this._optionsForExec();
952
+ if (utils.hasUserDefinedProperty(options, 'middleware')) {
953
+ const { middleware, ...cursorOptions } = options;
954
+ this.options.middleware = middleware;
955
+ options = cursorOptions;
956
+ }
914
957
  this.options.cursor = options || {};
915
958
  return new AggregationCursor(this); // return this;
916
959
  };
@@ -922,10 +965,10 @@ Aggregate.prototype.cursor = function(options) {
922
965
  *
923
966
  * const res = await Model.aggregate(pipeline).collation({ locale: 'en_US', strength: 1 });
924
967
  *
925
- * @param {Object} collation options
968
+ * @param {object} collation options
926
969
  * @return {Aggregate} this
927
970
  * @api public
928
- * @see mongodb https://mongodb.github.io/node-mongodb-native/4.9/interfaces/CollationOptions.html
971
+ * @see mongodb https://mongodb.github.io/node-mongodb-native/7.0/interfaces/CollationOptions.html
929
972
  */
930
973
 
931
974
  Aggregate.prototype.collation = function(collation) {
@@ -945,7 +988,7 @@ Aggregate.prototype.collation = function(collation) {
945
988
  *
946
989
  * // Output: { books: [...], price: [{...}, {...}] }
947
990
  *
948
- * @param {Object} facet options
991
+ * @param {object} facet options
949
992
  * @return {Aggregate} this
950
993
  * @see $facet https://www.mongodb.com/docs/manual/reference/operator/aggregation/facet/
951
994
  * @api public
@@ -971,7 +1014,7 @@ Aggregate.prototype.facet = function(options) {
971
1014
  *
972
1015
  * // Output: [{ plot: '...', title: '...' }]
973
1016
  *
974
- * @param {Object} $search options
1017
+ * @param {object} $search options
975
1018
  * @return {Aggregate} this
976
1019
  * @see $search https://www.mongodb.com/docs/atlas/atlas-search/tutorial/
977
1020
  * @api public
@@ -988,7 +1031,7 @@ Aggregate.prototype.search = function(options) {
988
1031
  *
989
1032
  * MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }]
990
1033
  *
991
- * @return {Array} The current pipeline similar to the operation that will be executed
1034
+ * @return {PipelineStage[]} The current pipeline similar to the operation that will be executed
992
1035
  * @api public
993
1036
  */
994
1037
 
@@ -997,69 +1040,122 @@ Aggregate.prototype.pipeline = function() {
997
1040
  };
998
1041
 
999
1042
  /**
1000
- * Executes the aggregate pipeline on the currently bound Model.
1043
+ * Returns the current pipeline as a `$unionWith`-safe pipeline.
1044
+ * Throws if this pipeline contains `$out` or `$merge`.
1001
1045
  *
1002
1046
  * #### Example:
1003
1047
  *
1004
- * aggregate.exec(callback);
1048
+ * const base = MyModel.aggregate().match({ test: 1 });
1049
+ * base.pipelineForUnionWith(); // [{ $match: { test: 1 } }]
1050
+ *
1051
+ * @return {PipelineStage[]} The current pipeline with `$unionWith` stage restrictions
1052
+ * @api public
1053
+ */
1054
+
1055
+ Aggregate.prototype.pipelineForUnionWith = function pipelineForUnionWith() {
1056
+ for (const stage of this._pipeline) {
1057
+ if (stage?.$out != null || stage?.$merge != null) {
1058
+ throw new MongooseError('Aggregate pipeline for $unionWith cannot include `$out` or `$merge` stages');
1059
+ }
1060
+ }
1061
+
1062
+ return this._pipeline;
1063
+ };
1064
+
1065
+ /**
1066
+ * Executes the aggregate pipeline on the currently bound Model.
1005
1067
  *
1006
- * // Because a promise is returned, the `callback` is optional.
1068
+ * #### Example:
1007
1069
  * const result = await aggregate.exec();
1008
1070
  *
1009
- * @param {Function} [callback]
1010
- * @return {Promise} Returns a Promise if no "callback" is given.
1071
+ * @return {Promise}
1011
1072
  * @api public
1012
1073
  */
1013
1074
 
1014
- Aggregate.prototype.exec = function(callback) {
1015
- if (!this._model) {
1016
- throw new Error('Aggregate not bound to any Model');
1075
+ Aggregate.prototype.exec = async function exec() {
1076
+ if (!this._model && !this._connection) {
1077
+ throw new MongooseError('Aggregate not bound to any Model');
1078
+ }
1079
+ if (typeof arguments[0] === 'function') {
1080
+ throw new MongooseError('Aggregate.prototype.exec() no longer accepts a callback');
1017
1081
  }
1082
+
1083
+ if (this._connection) {
1084
+ if (!this._pipeline.length) {
1085
+ throw new MongooseError('Aggregate has empty pipeline');
1086
+ }
1087
+
1088
+ this._optionsForExec();
1089
+
1090
+ const _this = this;
1091
+ return traceAggregate(async function maybeTracedConnectionAggregate() {
1092
+ const cursor = await _this._connection.client.db().aggregate(_this._pipeline, _this.options);
1093
+ return await cursor.toArray();
1094
+ }, () => ({
1095
+ operation: 'aggregate',
1096
+ database: _this._connection.name,
1097
+ serverAddress: _this._connection.host,
1098
+ serverPort: _this._connection.port,
1099
+ args: {
1100
+ pipeline: _this._pipeline,
1101
+ options: _this.options
1102
+ }
1103
+ }));
1104
+ }
1105
+
1018
1106
  const model = this._model;
1019
1107
  const collection = this._model.collection;
1020
1108
 
1021
- applyGlobalMaxTimeMS(this.options, model);
1022
- applyGlobalDiskUse(this.options, model);
1109
+ applyGlobalMaxTimeMS(this.options, model.db.options, model.base.options);
1110
+ applyGlobalDiskUse(this.options, model.db.options, model.base.options);
1111
+
1112
+ this._optionsForExec();
1023
1113
 
1024
- if (this.options && this.options.cursor) {
1114
+ if (this.options?.cursor) {
1025
1115
  return new AggregationCursor(this);
1026
1116
  }
1027
1117
 
1028
- return promiseOrCallback(callback, cb => {
1029
- prepareDiscriminatorPipeline(this._pipeline, this._model.schema);
1030
- stringifyFunctionOperators(this._pipeline);
1118
+ prepareDiscriminatorPipeline(this._pipeline, this._model.schema);
1119
+ stringifyFunctionOperators(this._pipeline);
1031
1120
 
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
- }
1121
+ const _this = this;
1122
+ return traceAggregate(async function maybeTracedAggregateExec() {
1123
+ const preFilter = buildMiddlewareFilter(_this.options, 'pre');
1124
+ const postFilter = buildMiddlewareFilter(_this.options, 'post');
1042
1125
 
1043
- const options = utils.clone(this.options || {});
1126
+ try {
1127
+ await model.hooks.execPre('aggregate', _this, [], { filter: preFilter });
1128
+ } catch (error) {
1129
+ return await model.hooks.execPost('aggregate', _this, [null], { error, filter: postFilter });
1130
+ }
1044
1131
 
1045
- collection.aggregate(this._pipeline, options, (err, cursor) => {
1046
- if (err != null) {
1047
- return cb(err);
1048
- }
1132
+ if (!_this._pipeline.length) {
1133
+ throw new MongooseError('Aggregate has empty pipeline');
1134
+ }
1049
1135
 
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
- }
1136
+ const { middleware, ...options } = clone(_this.options || {});
1056
1137
 
1057
- cb(null, result);
1058
- });
1059
- });
1060
- });
1061
- });
1062
- }, model.events);
1138
+ let result;
1139
+ try {
1140
+ const cursor = await collection.aggregate(_this._pipeline, options);
1141
+ result = await cursor.toArray();
1142
+ } catch (error) {
1143
+ return await model.hooks.execPost('aggregate', _this, [null], { error, filter: postFilter });
1144
+ }
1145
+
1146
+ await model.hooks.execPost('aggregate', _this, [result], { error: null, filter: postFilter });
1147
+ return result;
1148
+ }, () => ({
1149
+ operation: 'aggregate',
1150
+ collection: collection.name,
1151
+ database: model.db?.name,
1152
+ serverAddress: model.db?.host,
1153
+ serverPort: model.db?.port,
1154
+ args: {
1155
+ pipeline: _this._pipeline,
1156
+ options: _this.options
1157
+ }
1158
+ }));
1063
1159
  };
1064
1160
 
1065
1161
  /**
@@ -1079,9 +1175,9 @@ Aggregate.prototype.then = function(resolve, reject) {
1079
1175
  };
1080
1176
 
1081
1177
  /**
1082
- * Executes the query returning a `Promise` which will be
1178
+ * Executes the aggregation returning a `Promise` which will be
1083
1179
  * resolved with either the doc(s) or rejected with the error.
1084
- * Like [`.then()`](#query_Query-then), but only takes a rejection handler.
1180
+ * Like [`.then()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.then()), but only takes a rejection handler.
1085
1181
  * Compatible with `await`.
1086
1182
  *
1087
1183
  * @param {Function} [reject]
@@ -1093,6 +1189,21 @@ Aggregate.prototype.catch = function(reject) {
1093
1189
  return this.exec().then(null, reject);
1094
1190
  };
1095
1191
 
1192
+ /**
1193
+ * Executes the aggregate returning a `Promise` which will be
1194
+ * resolved with `.finally()` chained.
1195
+ *
1196
+ * More about [Promise `finally()` in JavaScript](https://thecodebarbarian.com/using-promise-finally-in-node-js.html).
1197
+ *
1198
+ * @param {Function} [onFinally]
1199
+ * @return {Promise}
1200
+ * @api public
1201
+ */
1202
+
1203
+ Aggregate.prototype.finally = function(onFinally) {
1204
+ return this.exec().finally(onFinally);
1205
+ };
1206
+
1096
1207
  /**
1097
1208
  * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js)
1098
1209
  * You do not need to call this function explicitly, the JavaScript runtime
@@ -1105,24 +1216,15 @@ Aggregate.prototype.catch = function(reject) {
1105
1216
  * console.log(doc.name);
1106
1217
  * }
1107
1218
  *
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
1219
  * @method [Symbol.asyncIterator]
1116
1220
  * @memberOf Aggregate
1117
1221
  * @instance
1118
1222
  * @api public
1119
1223
  */
1120
1224
 
1121
- if (Symbol.asyncIterator != null) {
1122
- Aggregate.prototype[Symbol.asyncIterator] = function() {
1123
- return this.cursor({ useMongooseAggCursor: true }).transformNull()._transformForAsyncIterator();
1124
- };
1125
- }
1225
+ Aggregate.prototype[Symbol.asyncIterator] = function() {
1226
+ return this.cursor({ useMongooseAggCursor: true }).transformNull()._transformForAsyncIterator();
1227
+ };
1126
1228
 
1127
1229
  /*!
1128
1230
  * Helpers
@@ -1131,8 +1233,8 @@ if (Symbol.asyncIterator != null) {
1131
1233
  /**
1132
1234
  * Checks whether an object is likely a pipeline operator
1133
1235
  *
1134
- * @param {Object} obj object to check
1135
- * @return {Boolean}
1236
+ * @param {object} obj object to check
1237
+ * @return {boolean}
1136
1238
  * @api private
1137
1239
  */
1138
1240