monsqlize 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +2474 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1368 -0
  4. package/index.d.ts +1052 -0
  5. package/lib/cache.js +491 -0
  6. package/lib/common/cursor.js +58 -0
  7. package/lib/common/docs-urls.js +72 -0
  8. package/lib/common/index-options.js +222 -0
  9. package/lib/common/log.js +60 -0
  10. package/lib/common/namespace.js +21 -0
  11. package/lib/common/normalize.js +33 -0
  12. package/lib/common/page-result.js +42 -0
  13. package/lib/common/runner.js +56 -0
  14. package/lib/common/server-features.js +231 -0
  15. package/lib/common/shape-builders.js +26 -0
  16. package/lib/common/validation.js +49 -0
  17. package/lib/connect.js +76 -0
  18. package/lib/constants.js +54 -0
  19. package/lib/count-queue.js +187 -0
  20. package/lib/distributed-cache-invalidator.js +259 -0
  21. package/lib/errors.js +157 -0
  22. package/lib/index.js +352 -0
  23. package/lib/logger.js +224 -0
  24. package/lib/model/examples/test.js +114 -0
  25. package/lib/mongodb/common/accessor-helpers.js +44 -0
  26. package/lib/mongodb/common/agg-pipeline.js +32 -0
  27. package/lib/mongodb/common/iid.js +27 -0
  28. package/lib/mongodb/common/lexicographic-expr.js +52 -0
  29. package/lib/mongodb/common/shape.js +31 -0
  30. package/lib/mongodb/common/sort.js +38 -0
  31. package/lib/mongodb/common/transaction-aware.js +24 -0
  32. package/lib/mongodb/connect.js +178 -0
  33. package/lib/mongodb/index.js +458 -0
  34. package/lib/mongodb/management/admin-ops.js +199 -0
  35. package/lib/mongodb/management/bookmark-ops.js +166 -0
  36. package/lib/mongodb/management/cache-ops.js +49 -0
  37. package/lib/mongodb/management/collection-ops.js +386 -0
  38. package/lib/mongodb/management/database-ops.js +201 -0
  39. package/lib/mongodb/management/index-ops.js +474 -0
  40. package/lib/mongodb/management/index.js +16 -0
  41. package/lib/mongodb/management/namespace.js +30 -0
  42. package/lib/mongodb/management/validation-ops.js +267 -0
  43. package/lib/mongodb/queries/aggregate.js +133 -0
  44. package/lib/mongodb/queries/chain.js +623 -0
  45. package/lib/mongodb/queries/count.js +88 -0
  46. package/lib/mongodb/queries/distinct.js +68 -0
  47. package/lib/mongodb/queries/find-and-count.js +183 -0
  48. package/lib/mongodb/queries/find-by-ids.js +235 -0
  49. package/lib/mongodb/queries/find-one-by-id.js +170 -0
  50. package/lib/mongodb/queries/find-one.js +61 -0
  51. package/lib/mongodb/queries/find-page.js +565 -0
  52. package/lib/mongodb/queries/find.js +161 -0
  53. package/lib/mongodb/queries/index.js +49 -0
  54. package/lib/mongodb/writes/delete-many.js +181 -0
  55. package/lib/mongodb/writes/delete-one.js +173 -0
  56. package/lib/mongodb/writes/find-one-and-delete.js +193 -0
  57. package/lib/mongodb/writes/find-one-and-replace.js +222 -0
  58. package/lib/mongodb/writes/find-one-and-update.js +223 -0
  59. package/lib/mongodb/writes/increment-one.js +243 -0
  60. package/lib/mongodb/writes/index.js +41 -0
  61. package/lib/mongodb/writes/insert-batch.js +498 -0
  62. package/lib/mongodb/writes/insert-many.js +218 -0
  63. package/lib/mongodb/writes/insert-one.js +171 -0
  64. package/lib/mongodb/writes/replace-one.js +199 -0
  65. package/lib/mongodb/writes/result-handler.js +236 -0
  66. package/lib/mongodb/writes/update-many.js +205 -0
  67. package/lib/mongodb/writes/update-one.js +207 -0
  68. package/lib/mongodb/writes/upsert-one.js +190 -0
  69. package/lib/multi-level-cache.js +189 -0
  70. package/lib/operators.js +330 -0
  71. package/lib/redis-cache-adapter.js +237 -0
  72. package/lib/transaction/CacheLockManager.js +161 -0
  73. package/lib/transaction/DistributedCacheLockManager.js +239 -0
  74. package/lib/transaction/Transaction.js +314 -0
  75. package/lib/transaction/TransactionManager.js +266 -0
  76. package/lib/transaction/index.js +10 -0
  77. package/package.json +111 -0
@@ -0,0 +1,623 @@
1
+ /**
2
+ * 链式调用构建器
3
+ * @description 提供 MongoDB 风格的链式调用 API,最终执行时会合并所有选项并利用缓存
4
+ */
5
+
6
+ const { createErrorMessage } = require('../../common/docs-urls');
7
+
8
+ /**
9
+ * FindChain 类 - find 查询的链式调用构建器
10
+ */
11
+ class FindChain {
12
+ /**
13
+ * 创建 FindChain 实例
14
+ * @param {Object} context - 上下文对象
15
+ * @param {Object} context.collection - MongoDB 集合实例
16
+ * @param {Object} context.defaults - 默认配置
17
+ * @param {Function} context.run - 缓存执行器
18
+ * @param {string} context.instanceId - 实例ID
19
+ * @param {string} context.effectiveDbName - 数据库名
20
+ * @param {Object} context.logger - 日志器
21
+ * @param {Function} context.emit - 事件发射器
22
+ * @param {Object} context.mongoSlowLogShaper - 慢查询日志格式化器
23
+ * @param {Object} query - 查询条件
24
+ * @param {Object} initialOptions - 初始查询选项
25
+ */
26
+ constructor(context, query = {}, initialOptions = {}) {
27
+ this._context = context;
28
+ this._query = query;
29
+ this._options = { ...initialOptions };
30
+ this._executed = false;
31
+ }
32
+
33
+ /**
34
+ * 设置返回文档数量限制
35
+ * @param {number} value - 限制数量
36
+ * @returns {FindChain} 返回自身以支持链式调用
37
+ */
38
+ limit(value) {
39
+ if (this._executed) {
40
+ throw new Error(createErrorMessage(
41
+ "Cannot call .limit() after query execution.\n" +
42
+ "Tip: Create a new chain for another query:\n" +
43
+ " const results = await collection('products').find({}).limit(10);",
44
+ 'chaining.limit'
45
+ ));
46
+ }
47
+ if (typeof value !== 'number' || value < 0) {
48
+ throw new Error(createErrorMessage(
49
+ `limit() requires a non-negative number, got: ${typeof value} (${value})\n` +
50
+ `Usage: .limit(10)`,
51
+ 'chaining.limit'
52
+ ));
53
+ }
54
+ this._options.limit = value;
55
+ return this;
56
+ }
57
+
58
+ /**
59
+ * 设置跳过的文档数量
60
+ * @param {number} value - 跳过数量
61
+ * @returns {FindChain} 返回自身以支持链式调用
62
+ */
63
+ skip(value) {
64
+ if (this._executed) {
65
+ throw new Error(createErrorMessage(
66
+ "Cannot call .skip() after query execution.\n" +
67
+ "Tip: Create a new chain for another query.",
68
+ 'chaining.skip'
69
+ ));
70
+ }
71
+ if (typeof value !== 'number' || value < 0) {
72
+ throw new Error(createErrorMessage(
73
+ `skip() requires a non-negative number, got: ${typeof value} (${value})\n` +
74
+ `Usage: .skip(10)`,
75
+ 'chaining.skip'
76
+ ));
77
+ }
78
+ this._options.skip = value;
79
+ return this;
80
+ }
81
+
82
+ /**
83
+ * 设置排序规则
84
+ * @param {Object|Array} value - 排序配置,如 { field: 1 } 或 [['field', 1]]
85
+ * @returns {FindChain} 返回自身以支持链式调用
86
+ */
87
+ sort(value) {
88
+ if (this._executed) {
89
+ throw new Error(createErrorMessage(
90
+ "Cannot call .sort() after query execution.",
91
+ 'chaining.sort'
92
+ ));
93
+ }
94
+ if (!value || (typeof value !== 'object')) {
95
+ throw new Error(createErrorMessage(
96
+ `sort() requires an object or array, got: ${typeof value}\n` +
97
+ `Usage: .sort({ price: -1, name: 1 })\n` +
98
+ `Note: Use 1 for ascending, -1 for descending`,
99
+ 'chaining.sort'
100
+ ));
101
+ }
102
+ this._options.sort = value;
103
+ return this;
104
+ }
105
+
106
+ /**
107
+ * 设置字段投影
108
+ * @param {Object|Array} value - 投影配置
109
+ * @returns {FindChain} 返回自身以支持链式调用
110
+ */
111
+ project(value) {
112
+ if (this._executed) {
113
+ throw new Error(createErrorMessage(
114
+ "Cannot call .project() after query execution.",
115
+ 'chaining.project'
116
+ ));
117
+ }
118
+ if (!value || typeof value !== 'object') {
119
+ throw new Error(createErrorMessage(
120
+ `project() requires an object or array, got: ${typeof value}\n` +
121
+ `Usage: .project({ name: 1, price: 1 })`,
122
+ 'chaining.project'
123
+ ));
124
+ }
125
+ this._options.projection = value;
126
+ return this;
127
+ }
128
+
129
+ /**
130
+ * 设置索引提示
131
+ * @param {Object|string} value - 索引名称或索引规格
132
+ * @returns {FindChain} 返回自身以支持链式调用
133
+ */
134
+ hint(value) {
135
+ if (this._executed) {
136
+ throw new Error(createErrorMessage(
137
+ "Cannot call .hint() after query execution.",
138
+ 'chaining.hint'
139
+ ));
140
+ }
141
+ if (!value) {
142
+ throw new Error(createErrorMessage(
143
+ "hint() requires an index name or specification\n" +
144
+ `Usage: .hint({ category: 1, price: -1 }) or .hint('category_1_price_-1')`,
145
+ 'chaining.hint'
146
+ ));
147
+ }
148
+ this._options.hint = value;
149
+ return this;
150
+ }
151
+
152
+ /**
153
+ * 设置排序规则
154
+ * @param {Object} value - 排序规则配置
155
+ * @returns {FindChain} 返回自身以支持链式调用
156
+ */
157
+ collation(value) {
158
+ if (this._executed) {
159
+ throw new Error(createErrorMessage(
160
+ "Cannot call .collation() after query execution.",
161
+ 'chaining.collation'
162
+ ));
163
+ }
164
+ if (!value || typeof value !== 'object') {
165
+ throw new Error(createErrorMessage(
166
+ `collation() requires an object, got: ${typeof value}\n` +
167
+ `Usage: .collation({ locale: 'zh', strength: 2 })`,
168
+ 'chaining.collation'
169
+ ));
170
+ }
171
+ this._options.collation = value;
172
+ return this;
173
+ }
174
+
175
+ /**
176
+ * 设置查询注释
177
+ * @param {string} value - 注释内容
178
+ * @returns {FindChain} 返回自身以支持链式调用
179
+ */
180
+ comment(value) {
181
+ if (this._executed) {
182
+ throw new Error(createErrorMessage(
183
+ "Cannot call .comment() after query execution.",
184
+ 'chaining.comment'
185
+ ));
186
+ }
187
+ if (typeof value !== 'string') {
188
+ throw new Error(createErrorMessage(
189
+ `comment() requires a string, got: ${typeof value}\n` +
190
+ `Usage: .comment('UserAPI:getProducts:user_123')`,
191
+ 'chaining.comment'
192
+ ));
193
+ }
194
+ this._options.comment = value;
195
+ return this;
196
+ }
197
+
198
+ /**
199
+ * 设置查询超时时间
200
+ * @param {number} value - 超时时间(毫秒)
201
+ * @returns {FindChain} 返回自身以支持链式调用
202
+ */
203
+ maxTimeMS(value) {
204
+ if (this._executed) {
205
+ throw new Error(createErrorMessage(
206
+ "Cannot call .maxTimeMS() after query execution.",
207
+ 'chaining.maxTimeMS'
208
+ ));
209
+ }
210
+ if (typeof value !== 'number' || value < 0) {
211
+ throw new Error(createErrorMessage(
212
+ `maxTimeMS() requires a non-negative number, got: ${typeof value} (${value})\n` +
213
+ `Usage: .maxTimeMS(5000) // 5 seconds`,
214
+ 'chaining.maxTimeMS'
215
+ ));
216
+ }
217
+ this._options.maxTimeMS = value;
218
+ return this;
219
+ }
220
+
221
+ /**
222
+ * 设置批处理大小
223
+ * @param {number} value - 批处理大小
224
+ * @returns {FindChain} 返回自身以支持链式调用
225
+ */
226
+ batchSize(value) {
227
+ if (this._executed) {
228
+ throw new Error(createErrorMessage(
229
+ "Cannot call .batchSize() after query execution.",
230
+ 'chaining.batchSize'
231
+ ));
232
+ }
233
+ if (typeof value !== 'number' || value < 0) {
234
+ throw new Error(createErrorMessage(
235
+ `batchSize() requires a non-negative number, got: ${typeof value} (${value})\n` +
236
+ `Usage: .batchSize(1000)`,
237
+ 'chaining.batchSize'
238
+ ));
239
+ }
240
+ this._options.batchSize = value;
241
+ return this;
242
+ }
243
+
244
+ /**
245
+ * 返回查询执行计划
246
+ * @param {string} [verbosity='queryPlanner'] - 详细级别
247
+ * @returns {Promise<Object>} 执行计划
248
+ */
249
+ async explain(verbosity = 'queryPlanner') {
250
+ const { normalizeProjection, normalizeSort } = require('../../common/normalize');
251
+ const { collection, defaults } = this._context;
252
+
253
+ // 标准化选项
254
+ const projection = normalizeProjection(this._options.projection);
255
+ const sort = normalizeSort(this._options.sort);
256
+ const limit = this._options.limit !== undefined ? this._options.limit : defaults.findLimit;
257
+ const skip = this._options.skip;
258
+ const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
259
+
260
+ const driverOpts = { projection, sort, skip, maxTimeMS };
261
+ if (this._options.hint) driverOpts.hint = this._options.hint;
262
+ if (this._options.collation) driverOpts.collation = this._options.collation;
263
+ if (limit !== undefined) driverOpts.limit = limit;
264
+ if (this._options.batchSize !== undefined) driverOpts.batchSize = this._options.batchSize;
265
+ if (this._options.comment) driverOpts.comment = this._options.comment;
266
+
267
+ const cursor = collection.find(this._query, driverOpts);
268
+ return cursor.explain(verbosity);
269
+ }
270
+
271
+ /**
272
+ * 返回流式结果
273
+ * @returns {ReadableStream} MongoDB 游标流
274
+ */
275
+ stream() {
276
+ const { normalizeProjection, normalizeSort } = require('../../common/normalize');
277
+ const { collection, defaults } = this._context;
278
+
279
+ // 标准化选项
280
+ const projection = normalizeProjection(this._options.projection);
281
+ const sort = normalizeSort(this._options.sort);
282
+ const limit = this._options.limit !== undefined ? this._options.limit : defaults.findLimit;
283
+ const skip = this._options.skip;
284
+ const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
285
+
286
+ const driverOpts = { projection, sort, skip, maxTimeMS };
287
+ if (this._options.hint) driverOpts.hint = this._options.hint;
288
+ if (this._options.collation) driverOpts.collation = this._options.collation;
289
+ if (limit !== undefined) driverOpts.limit = limit;
290
+ if (this._options.batchSize !== undefined) driverOpts.batchSize = this._options.batchSize;
291
+ if (this._options.comment) driverOpts.comment = this._options.comment;
292
+
293
+ const cursor = collection.find(this._query, driverOpts);
294
+ return cursor.stream();
295
+ }
296
+
297
+ /**
298
+ * 执行查询并返回结果数组
299
+ * @returns {Promise<Array>} 查询结果数组
300
+ */
301
+ async toArray() {
302
+ if (this._executed) {
303
+ throw new Error(createErrorMessage(
304
+ "Query already executed. Create a new chain for another query.\n" +
305
+ "Tip: Each chain can only be executed once:\n" +
306
+ " const results1 = await collection('products').find({}).limit(10);\n" +
307
+ " const results2 = await collection('products').find({}).limit(20); // Create new chain",
308
+ 'chaining.toArray'
309
+ ));
310
+ }
311
+
312
+ const { normalizeProjection, normalizeSort } = require('../../common/normalize');
313
+ const { collection, defaults, run } = this._context;
314
+
315
+ // 标准化选项
316
+ this._options.projection = normalizeProjection(this._options.projection);
317
+ const sort = normalizeSort(this._options.sort);
318
+ const limit = this._options.limit !== undefined ? this._options.limit : defaults.findLimit;
319
+ const skip = this._options.skip;
320
+ const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
321
+
322
+ const driverOpts = {
323
+ projection: this._options.projection,
324
+ sort,
325
+ skip,
326
+ maxTimeMS
327
+ };
328
+ if (this._options.hint) driverOpts.hint = this._options.hint;
329
+ if (this._options.collation) driverOpts.collation = this._options.collation;
330
+ if (limit !== undefined) driverOpts.limit = limit;
331
+ if (this._options.batchSize !== undefined) driverOpts.batchSize = this._options.batchSize;
332
+ if (this._options.comment) driverOpts.comment = this._options.comment;
333
+
334
+ this._executed = true;
335
+
336
+ // 使用 run 执行器(支持缓存)
337
+ return run(
338
+ 'find',
339
+ { query: this._query, ...this._options },
340
+ async () => collection.find(this._query, driverOpts).toArray()
341
+ );
342
+ }
343
+
344
+ /**
345
+ * 使 FindChain 可以作为 Promise 使用
346
+ * @returns {Promise<Array>} 查询结果数组
347
+ */
348
+ then(resolve, reject) {
349
+ return this.toArray().then(resolve, reject);
350
+ }
351
+
352
+ /**
353
+ * 支持 catch 方法
354
+ */
355
+ catch(reject) {
356
+ return this.toArray().catch(reject);
357
+ }
358
+
359
+ /**
360
+ * 支持 finally 方法
361
+ */
362
+ finally(fn) {
363
+ return this.toArray().finally(fn);
364
+ }
365
+ }
366
+
367
+ /**
368
+ * AggregateChain 类 - aggregate 查询的链式调用构建器
369
+ */
370
+ class AggregateChain {
371
+ /**
372
+ * 创建 AggregateChain 实例
373
+ * @param {Object} context - 上下文对象
374
+ * @param {Array} pipeline - 聚合管道
375
+ * @param {Object} initialOptions - 初始选项
376
+ */
377
+ constructor(context, pipeline = [], initialOptions = {}) {
378
+ this._context = context;
379
+ this._pipeline = pipeline;
380
+ this._options = { ...initialOptions };
381
+ this._executed = false;
382
+ }
383
+
384
+ /**
385
+ * 设置索引提示
386
+ * @param {Object|string} value - 索引名称或索引规格
387
+ * @returns {AggregateChain} 返回自身以支持链式调用
388
+ */
389
+ hint(value) {
390
+ if (this._executed) {
391
+ throw new Error(createErrorMessage(
392
+ "Cannot call .hint() after query execution.",
393
+ 'chaining.hint'
394
+ ));
395
+ }
396
+ if (!value) {
397
+ throw new Error(createErrorMessage(
398
+ "hint() requires an index name or specification\n" +
399
+ `Usage: .hint({ status: 1, createdAt: -1 })`,
400
+ 'chaining.hint'
401
+ ));
402
+ }
403
+ this._options.hint = value;
404
+ return this;
405
+ }
406
+
407
+ /**
408
+ * 设置排序规则
409
+ * @param {Object} value - 排序规则配置
410
+ * @returns {AggregateChain} 返回自身以支持链式调用
411
+ */
412
+ collation(value) {
413
+ if (this._executed) {
414
+ throw new Error(createErrorMessage(
415
+ "Cannot call .collation() after query execution.",
416
+ 'chaining.collation'
417
+ ));
418
+ }
419
+ if (!value || typeof value !== 'object') {
420
+ throw new Error(createErrorMessage(
421
+ `collation() requires an object, got: ${typeof value}\n` +
422
+ `Usage: .collation({ locale: 'zh', strength: 2 })`,
423
+ 'chaining.collation'
424
+ ));
425
+ }
426
+ this._options.collation = value;
427
+ return this;
428
+ }
429
+
430
+ /**
431
+ * 设置查询注释
432
+ * @param {string} value - 注释内容
433
+ * @returns {AggregateChain} 返回自身以支持链式调用
434
+ */
435
+ comment(value) {
436
+ if (this._executed) {
437
+ throw new Error(createErrorMessage(
438
+ "Cannot call .comment() after query execution.",
439
+ 'chaining.comment'
440
+ ));
441
+ }
442
+ if (typeof value !== 'string') {
443
+ throw new Error(createErrorMessage(
444
+ `comment() requires a string, got: ${typeof value}\n` +
445
+ `Usage: .comment('OrderAPI:aggregateSales')`,
446
+ 'chaining.comment'
447
+ ));
448
+ }
449
+ this._options.comment = value;
450
+ return this;
451
+ }
452
+
453
+ /**
454
+ * 设置查询超时时间
455
+ * @param {number} value - 超时时间(毫秒)
456
+ * @returns {AggregateChain} 返回自身以支持链式调用
457
+ */
458
+ maxTimeMS(value) {
459
+ if (this._executed) {
460
+ throw new Error(createErrorMessage(
461
+ "Cannot call .maxTimeMS() after query execution.",
462
+ 'chaining.maxTimeMS'
463
+ ));
464
+ }
465
+ if (typeof value !== 'number' || value < 0) {
466
+ throw new Error(createErrorMessage(
467
+ `maxTimeMS() requires a non-negative number, got: ${typeof value} (${value})\n` +
468
+ `Usage: .maxTimeMS(10000) // 10 seconds`,
469
+ 'chaining.maxTimeMS'
470
+ ));
471
+ }
472
+ this._options.maxTimeMS = value;
473
+ return this;
474
+ }
475
+
476
+ /**
477
+ * 设置是否允许使用磁盘
478
+ * @param {boolean} value - 是否允许
479
+ * @returns {AggregateChain} 返回自身以支持链式调用
480
+ */
481
+ allowDiskUse(value) {
482
+ if (this._executed) {
483
+ throw new Error(createErrorMessage(
484
+ "Cannot call .allowDiskUse() after query execution.",
485
+ 'chaining.allowDiskUse'
486
+ ));
487
+ }
488
+ if (typeof value !== 'boolean') {
489
+ throw new Error(createErrorMessage(
490
+ `allowDiskUse() requires a boolean, got: ${typeof value}\n` +
491
+ `Usage: .allowDiskUse(true)`,
492
+ 'chaining.allowDiskUse'
493
+ ));
494
+ }
495
+ this._options.allowDiskUse = value;
496
+ return this;
497
+ }
498
+
499
+ /**
500
+ * 设置批处理大小
501
+ * @param {number} value - 批处理大小
502
+ * @returns {AggregateChain} 返回自身以支持链式调用
503
+ */
504
+ batchSize(value) {
505
+ if (this._executed) {
506
+ throw new Error(createErrorMessage(
507
+ "Cannot call .batchSize() after query execution.",
508
+ 'chaining.batchSize'
509
+ ));
510
+ }
511
+ if (typeof value !== 'number' || value < 0) {
512
+ throw new Error(createErrorMessage(
513
+ `batchSize() requires a non-negative number, got: ${typeof value} (${value})\n` +
514
+ `Usage: .batchSize(1000)`,
515
+ 'chaining.batchSize'
516
+ ));
517
+ }
518
+ this._options.batchSize = value;
519
+ return this;
520
+ }
521
+
522
+ /**
523
+ * 返回查询执行计划
524
+ * @param {string} [verbosity='queryPlanner'] - 详细级别
525
+ * @returns {Promise<Object>} 执行计划
526
+ */
527
+ async explain(verbosity = 'queryPlanner') {
528
+ const { collection, defaults } = this._context;
529
+
530
+ const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
531
+ const allowDiskUse = this._options.allowDiskUse !== undefined ? this._options.allowDiskUse : false;
532
+
533
+ const aggOptions = { maxTimeMS, allowDiskUse };
534
+ if (this._options.collation) aggOptions.collation = this._options.collation;
535
+ if (this._options.hint) aggOptions.hint = this._options.hint;
536
+ if (this._options.comment) aggOptions.comment = this._options.comment;
537
+ if (this._options.batchSize !== undefined) aggOptions.batchSize = this._options.batchSize;
538
+
539
+ const cursor = collection.aggregate(this._pipeline, aggOptions);
540
+ return cursor.explain(verbosity);
541
+ }
542
+
543
+ /**
544
+ * 返回流式结果
545
+ * @returns {ReadableStream} MongoDB 游标流
546
+ */
547
+ stream() {
548
+ const { collection, defaults } = this._context;
549
+
550
+ const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
551
+ const allowDiskUse = this._options.allowDiskUse !== undefined ? this._options.allowDiskUse : false;
552
+
553
+ const aggOptions = { maxTimeMS, allowDiskUse };
554
+ if (this._options.collation) aggOptions.collation = this._options.collation;
555
+ if (this._options.hint) aggOptions.hint = this._options.hint;
556
+ if (this._options.comment) aggOptions.comment = this._options.comment;
557
+ if (this._options.batchSize !== undefined) aggOptions.batchSize = this._options.batchSize;
558
+
559
+ const cursor = collection.aggregate(this._pipeline, aggOptions);
560
+ return cursor.stream();
561
+ }
562
+
563
+ /**
564
+ * 执行聚合并返回结果数组
565
+ * @returns {Promise<Array>} 聚合结果数组
566
+ */
567
+ async toArray() {
568
+ if (this._executed) {
569
+ throw new Error(createErrorMessage(
570
+ "Query already executed. Create a new chain for another query.\n" +
571
+ "Tip: Each chain can only be executed once:\n" +
572
+ " const results1 = await collection('orders').aggregate([...]).allowDiskUse(true);\n" +
573
+ " const results2 = await collection('orders').aggregate([...]).maxTimeMS(5000); // Create new chain",
574
+ 'chaining.toArray'
575
+ ));
576
+ }
577
+
578
+ const { collection, defaults, run } = this._context;
579
+
580
+ const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
581
+ const allowDiskUse = this._options.allowDiskUse !== undefined ? this._options.allowDiskUse : false;
582
+
583
+ const aggOptions = { maxTimeMS, allowDiskUse };
584
+ if (this._options.collation) aggOptions.collation = this._options.collation;
585
+ if (this._options.hint) aggOptions.hint = this._options.hint;
586
+ if (this._options.comment) aggOptions.comment = this._options.comment;
587
+ if (this._options.batchSize !== undefined) aggOptions.batchSize = this._options.batchSize;
588
+
589
+ this._executed = true;
590
+
591
+ // 使用 run 执行器(支持缓存)
592
+ return run(
593
+ 'aggregate',
594
+ this._options,
595
+ async () => collection.aggregate(this._pipeline, aggOptions).toArray()
596
+ );
597
+ }
598
+
599
+ /**
600
+ * 使 AggregateChain 可以作为 Promise 使用
601
+ * @returns {Promise<Array>} 聚合结果数组
602
+ */
603
+ then(resolve, reject) {
604
+ return this.toArray().then(resolve, reject);
605
+ }
606
+
607
+ /**
608
+ * 支持 catch 方法
609
+ */
610
+ catch(reject) {
611
+ return this.toArray().catch(reject);
612
+ }
613
+
614
+ /**
615
+ * 支持 finally 方法
616
+ */
617
+ finally(fn) {
618
+ return this.toArray().finally(fn);
619
+ }
620
+ }
621
+
622
+ module.exports = { FindChain, AggregateChain };
623
+