monsqlize 1.3.0 → 2.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 (172) hide show
  1. package/CHANGELOG.md +56 -60
  2. package/LICENSE +201 -21
  3. package/README.md +537 -1828
  4. package/changelogs/README.md +160 -0
  5. package/changelogs/v2.0.0.md +222 -0
  6. package/dist/cjs/index.cjs +10600 -0
  7. package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
  8. package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
  9. package/dist/cjs/transaction/Transaction.cjs +158 -0
  10. package/dist/cjs/transaction/TransactionManager.cjs +298 -0
  11. package/dist/esm/index.mjs +10650 -0
  12. package/dist/types/base.d.ts +81 -0
  13. package/dist/types/collection.d.ts +1031 -0
  14. package/dist/types/expression.d.ts +115 -0
  15. package/dist/types/index.d.ts +23 -0
  16. package/dist/types/lock.d.ts +74 -0
  17. package/dist/types/model.d.ts +526 -0
  18. package/dist/types/mongodb.d.ts +49 -0
  19. package/dist/types/monsqlize.d.ts +491 -0
  20. package/dist/types/pool.d.ts +84 -0
  21. package/dist/types/runtime.d.ts +362 -0
  22. package/dist/types/saga.d.ts +143 -0
  23. package/dist/types/slow-query-log.d.ts +126 -0
  24. package/dist/types/sync.d.ts +103 -0
  25. package/dist/types/transaction.d.ts +132 -0
  26. package/package.json +67 -69
  27. package/index.d.ts +0 -206
  28. package/index.mjs +0 -52
  29. package/lib/cache-invalidation.js +0 -279
  30. package/lib/cache.js +0 -530
  31. package/lib/common/cursor.js +0 -59
  32. package/lib/common/docs-urls.js +0 -73
  33. package/lib/common/index-options.js +0 -223
  34. package/lib/common/log.js +0 -61
  35. package/lib/common/namespace.js +0 -22
  36. package/lib/common/normalize.js +0 -34
  37. package/lib/common/page-result.js +0 -43
  38. package/lib/common/runner.js +0 -57
  39. package/lib/common/server-features.js +0 -232
  40. package/lib/common/shape-builders.js +0 -27
  41. package/lib/common/validation.js +0 -113
  42. package/lib/connect.js +0 -99
  43. package/lib/constants.js +0 -55
  44. package/lib/count-queue.js +0 -188
  45. package/lib/distributed-cache-invalidator.js +0 -260
  46. package/lib/errors.js +0 -168
  47. package/lib/expression/cache/ExpressionCache.js +0 -114
  48. package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
  49. package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
  50. package/lib/expression/detector.js +0 -84
  51. package/lib/expression/factory.js +0 -29
  52. package/lib/expression/index.js +0 -19
  53. package/lib/function-cache.js +0 -533
  54. package/lib/index.js +0 -1251
  55. package/lib/infrastructure/ConnectionPoolManager.js +0 -464
  56. package/lib/infrastructure/HealthChecker.js +0 -281
  57. package/lib/infrastructure/PoolConfig.js +0 -199
  58. package/lib/infrastructure/PoolSelector.js +0 -225
  59. package/lib/infrastructure/PoolStats.js +0 -244
  60. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
  61. package/lib/infrastructure/ssh-tunnel.js +0 -41
  62. package/lib/infrastructure/uri-parser.js +0 -36
  63. package/lib/lock/Lock.js +0 -67
  64. package/lib/lock/errors.js +0 -28
  65. package/lib/lock/index.js +0 -13
  66. package/lib/logger.js +0 -225
  67. package/lib/model/examples/test.js +0 -311
  68. package/lib/model/features/defaults.js +0 -161
  69. package/lib/model/features/populate.js +0 -568
  70. package/lib/model/features/relations.js +0 -120
  71. package/lib/model/features/soft-delete.js +0 -349
  72. package/lib/model/features/version.js +0 -157
  73. package/lib/model/features/virtuals.js +0 -219
  74. package/lib/model/index.js +0 -1265
  75. package/lib/mongodb/common/accessor-helpers.js +0 -59
  76. package/lib/mongodb/common/agg-pipeline.js +0 -36
  77. package/lib/mongodb/common/aggregation-validator.js +0 -127
  78. package/lib/mongodb/common/iid.js +0 -28
  79. package/lib/mongodb/common/lexicographic-expr.js +0 -53
  80. package/lib/mongodb/common/shape.js +0 -32
  81. package/lib/mongodb/common/sort.js +0 -39
  82. package/lib/mongodb/common/transaction-aware.js +0 -25
  83. package/lib/mongodb/connect.js +0 -234
  84. package/lib/mongodb/index.js +0 -639
  85. package/lib/mongodb/management/admin-ops.js +0 -200
  86. package/lib/mongodb/management/bookmark-ops.js +0 -167
  87. package/lib/mongodb/management/cache-ops.js +0 -50
  88. package/lib/mongodb/management/collection-ops.js +0 -387
  89. package/lib/mongodb/management/database-ops.js +0 -202
  90. package/lib/mongodb/management/index-ops.js +0 -475
  91. package/lib/mongodb/management/index.js +0 -17
  92. package/lib/mongodb/management/namespace.js +0 -31
  93. package/lib/mongodb/management/validation-ops.js +0 -268
  94. package/lib/mongodb/queries/aggregate.js +0 -172
  95. package/lib/mongodb/queries/chain.js +0 -631
  96. package/lib/mongodb/queries/count.js +0 -99
  97. package/lib/mongodb/queries/distinct.js +0 -78
  98. package/lib/mongodb/queries/find-and-count.js +0 -193
  99. package/lib/mongodb/queries/find-by-ids.js +0 -236
  100. package/lib/mongodb/queries/find-one-by-id.js +0 -171
  101. package/lib/mongodb/queries/find-one.js +0 -71
  102. package/lib/mongodb/queries/find-page.js +0 -618
  103. package/lib/mongodb/queries/find.js +0 -171
  104. package/lib/mongodb/queries/index.js +0 -51
  105. package/lib/mongodb/queries/watch.js +0 -538
  106. package/lib/mongodb/writes/common/batch-retry.js +0 -65
  107. package/lib/mongodb/writes/delete-batch.js +0 -323
  108. package/lib/mongodb/writes/delete-many.js +0 -181
  109. package/lib/mongodb/writes/delete-one.js +0 -173
  110. package/lib/mongodb/writes/find-one-and-delete.js +0 -203
  111. package/lib/mongodb/writes/find-one-and-replace.js +0 -239
  112. package/lib/mongodb/writes/find-one-and-update.js +0 -240
  113. package/lib/mongodb/writes/increment-one.js +0 -259
  114. package/lib/mongodb/writes/index.js +0 -46
  115. package/lib/mongodb/writes/insert-batch.js +0 -508
  116. package/lib/mongodb/writes/insert-many.js +0 -223
  117. package/lib/mongodb/writes/insert-one.js +0 -169
  118. package/lib/mongodb/writes/replace-one.js +0 -226
  119. package/lib/mongodb/writes/result-handler.js +0 -237
  120. package/lib/mongodb/writes/update-batch.js +0 -416
  121. package/lib/mongodb/writes/update-many.js +0 -275
  122. package/lib/mongodb/writes/update-one.js +0 -273
  123. package/lib/mongodb/writes/upsert-one.js +0 -203
  124. package/lib/multi-level-cache.js +0 -244
  125. package/lib/operators.js +0 -330
  126. package/lib/redis-cache-adapter.js +0 -267
  127. package/lib/saga/SagaContext.js +0 -67
  128. package/lib/saga/SagaDefinition.js +0 -32
  129. package/lib/saga/SagaExecutor.js +0 -201
  130. package/lib/saga/SagaOrchestrator.js +0 -186
  131. package/lib/saga/index.js +0 -11
  132. package/lib/slow-query-log/base-storage.js +0 -70
  133. package/lib/slow-query-log/batch-queue.js +0 -97
  134. package/lib/slow-query-log/config-manager.js +0 -196
  135. package/lib/slow-query-log/index.js +0 -238
  136. package/lib/slow-query-log/mongodb-storage.js +0 -324
  137. package/lib/slow-query-log/query-hash.js +0 -39
  138. package/lib/sync/ChangeStreamSyncManager.js +0 -405
  139. package/lib/sync/ResumeTokenStore.js +0 -192
  140. package/lib/sync/SyncConfig.js +0 -127
  141. package/lib/sync/SyncTarget.js +0 -240
  142. package/lib/sync/index.js +0 -20
  143. package/lib/transaction/CacheLockManager.js +0 -162
  144. package/lib/transaction/DistributedCacheLockManager.js +0 -475
  145. package/lib/transaction/Transaction.js +0 -315
  146. package/lib/transaction/TransactionManager.js +0 -267
  147. package/lib/transaction/index.js +0 -11
  148. package/lib/utils/objectid-converter.js +0 -632
  149. package/types/README.md +0 -122
  150. package/types/base.ts +0 -94
  151. package/types/batch.ts +0 -187
  152. package/types/cache.ts +0 -71
  153. package/types/chain.ts +0 -254
  154. package/types/collection.ts +0 -357
  155. package/types/expression.ts +0 -109
  156. package/types/function-cache.d.ts +0 -135
  157. package/types/lock.ts +0 -95
  158. package/types/model/definition.ts +0 -152
  159. package/types/model/index.ts +0 -10
  160. package/types/model/instance.ts +0 -121
  161. package/types/model/relations.ts +0 -121
  162. package/types/model/virtuals.ts +0 -32
  163. package/types/monsqlize.ts +0 -245
  164. package/types/options.ts +0 -192
  165. package/types/pagination.ts +0 -154
  166. package/types/pool.ts +0 -125
  167. package/types/query.ts +0 -71
  168. package/types/saga.ts +0 -125
  169. package/types/stream.ts +0 -64
  170. package/types/sync.ts +0 -79
  171. package/types/transaction.ts +0 -79
  172. package/types/write.ts +0 -77
@@ -1,275 +0,0 @@
1
- /**
2
- * updateMany 操作实现
3
- * 更新所有匹配的文档
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
9
- const { convertObjectIdStrings, convertUpdateDocument } = require('../../utils/objectid-converter');
10
- const { validateAggregationPipeline, isAggregationPipeline } = require('../common/aggregation-validator');
11
-
12
- /**
13
- * 创建 updateMany 操作
14
- * @param {Object} context - 模块上下文
15
- * @param {Object} context.db - MongoDB 数据库实例
16
- * @param {Object} context.cache - 缓存实例
17
- * @param {Object} context.logger - 日志实例
18
- * @param {Object} context.defaults - 默认配置
19
- * @param {string} context.collection - 集合名称
20
- * @param {string} context.effectiveDbName - 数据库名称
21
- * @param {string} context.instanceId - 实例ID
22
- * @returns {Object} 包含 updateMany 方法的对象
23
- */
24
- function createUpdateManyOps(context) {
25
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
26
-
27
- // 提取集合名称和原生 collection 对象
28
- const collectionName = collection.collectionName;
29
- const nativeCollection = collection;
30
-
31
- /**
32
- * 更新多个文档
33
- * @param {Object} filter - 筛选条件(必需)
34
- * @param {Object} update - 更新操作(必需,使用更新操作符如 $set)
35
- * @param {Object} [options] - 操作选项
36
- * @param {boolean} [options.upsert=false] - 不存在时是否插入
37
- * @param {Object} [options.writeConcern] - 写关注选项
38
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
39
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
40
- * @param {Object} [options.collation] - 排序规则
41
- * @param {Array|Object} [options.arrayFilters] - 数组过滤器
42
- * @param {Object} [options.hint] - 索引提示
43
- * @returns {Promise<Object>} 更新结果 { acknowledged, matchedCount, modifiedCount, upsertedId?, upsertedCount? }
44
- * @throws {Error} 当参数无效时
45
- *
46
- * @example
47
- * const result = await collection("users").updateMany(
48
- * { status: "inactive" },
49
- * { $set: { status: "archived", archivedAt: new Date() } }
50
- * );
51
- * console.log("Modified:", result.modifiedCount, "documents");
52
- *
53
- * @example
54
- * // 使用数组过滤器
55
- * const result = await collection("users").updateMany(
56
- * { "tags.name": "premium" },
57
- * { $set: { "tags.$[elem].verified": true } },
58
- * { arrayFilters: [{ "elem.name": "premium" }] }
59
- * );
60
- */
61
- const updateMany = async function updateMany(filter, update, options = {}) {
62
- const startTime = Date.now();
63
-
64
- // 1. 参数验证
65
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
66
- throw createError(
67
- ErrorCodes.INVALID_ARGUMENT,
68
- 'filter 必须是对象类型',
69
- [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
70
- );
71
- }
72
-
73
- if (!update || (typeof update !== 'object' && !Array.isArray(update))) {
74
- throw createError(
75
- ErrorCodes.INVALID_ARGUMENT,
76
- 'update 必须是对象(更新操作符)或数组(聚合管道)',
77
- [{ field: 'update', type: 'object|array.required', message: 'update 必须是更新操作符对象或聚合管道数组' }]
78
- );
79
- }
80
-
81
- // 检测聚合管道模式
82
- const isAggregation = isAggregationPipeline(update);
83
-
84
- if (isAggregation) {
85
- // 验证聚合管道格式
86
- validateAggregationPipeline(update);
87
-
88
- if (logger && logger.debug) {
89
- logger.debug(`[updateMany] 使用聚合管道模式`, {
90
- collection: collectionName,
91
- stagesCount: update.length,
92
- operators: update.map(stage => Object.keys(stage)[0])
93
- });
94
- }
95
- } else {
96
- // 验证 update 包含更新操作符(防止整体替换)
97
- const updateKeys = Object.keys(update);
98
-
99
- // 检查空对象
100
- if (updateKeys.length === 0) {
101
- throw createError(
102
- ErrorCodes.INVALID_ARGUMENT,
103
- 'update 不能为空对象',
104
- [{ field: 'update', type: 'object.empty', message: 'update 必须包含至少一个更新操作符,如 $set、$inc、$push 等' }]
105
- );
106
- }
107
-
108
- // 检查是否包含操作符
109
- if (!updateKeys.some(key => key.startsWith('$'))) {
110
- throw createError(
111
- ErrorCodes.INVALID_ARGUMENT,
112
- 'update 必须使用更新操作符(如 $set, $inc 等)',
113
- [{ field: 'update', type: 'object.invalid', message: '请使用 $set, $inc, $push 等更新操作符' }]
114
- );
115
- }
116
- }
117
-
118
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
119
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
120
- logger: context.logger,
121
- excludeFields: context.autoConvertConfig?.excludeFields,
122
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
123
- maxDepth: context.autoConvertConfig?.maxDepth
124
- });
125
-
126
- // ✅ v1.0.8: 聚合管道不转换 ObjectId(保持原样)
127
- const convertedUpdate = isAggregation
128
- ? update // 聚合管道保持原样
129
- : convertUpdateDocument(update, {
130
- logger: context.logger,
131
- excludeFields: context.autoConvertConfig?.excludeFields,
132
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
133
- maxDepth: context.autoConvertConfig?.maxDepth
134
- });
135
-
136
- // 2. 构建操作上下文
137
- const operation = 'updateMany';
138
- const ns = `${databaseName}.${collectionName}`;
139
-
140
- try {
141
- // 3. 执行批量更新操作
142
- const result = await nativeCollection.updateMany(convertedFilter, convertedUpdate, options);
143
-
144
- // 4. 自动失效缓存(只要有匹配或 upsert 插入,就失效缓存)
145
- // ✅ v1.1.6: 修复 upsert 场景的缓存失效问题 - 检查 matchedCount 或 upsertedId
146
- if (cache && (result.matchedCount > 0 || result.upsertedId)) {
147
- try {
148
- // 🆕 v1.1.6: 解析精准失效配置
149
- const instanceAuto = context.cacheAutoInvalidate || false;
150
- const queryAuto = options.autoInvalidate;
151
- const shouldAuto = queryAuto !== undefined ? queryAuto : instanceAuto;
152
-
153
-
154
- if (shouldAuto) {
155
- // 精准失效:updateMany 使用 filter 来匹配缓存
156
- // 注意:不使用 mergeFilterAndUpdate,因为更新后的文档可能不匹配原查询
157
- const CacheInvalidationEngine = require('../../cache-invalidation');
158
-
159
- const deleted = await CacheInvalidationEngine.invalidatePrecise(cache, {
160
- instanceId,
161
- type: 'mongodb',
162
- db: databaseName,
163
- collection: collectionName,
164
- document: convertedFilter, // 使用 filter 来匹配
165
- operation: result.upsertedId ? 'upsert' : 'updateMany'
166
- });
167
-
168
- if (deleted > 0) {
169
- logger.debug(`[${operation}] 精准失效缓存: ${databaseName}.${collectionName}, 删除 ${deleted} 个缓存键${result.upsertedId ? ' (upsert)' : ''}`);
170
- }
171
- } else {
172
- logger.debug(`[${operation}] 跳过自动失效(autoInvalidate=false)`);
173
- }
174
- } catch (cacheErr) {
175
- // 缓存失效失败不影响写操作
176
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, {
177
- ns: `${databaseName}.${collectionName}`,
178
- error: cacheErr,
179
- upserted: !!result.upsertedId
180
- });
181
- }
182
- }
183
-
184
- // 5. 记录慢操作日志
185
- const duration = Date.now() - startTime;
186
- const slowQueryMs = defaults.slowQueryMs || 1000;
187
- if (duration > slowQueryMs) {
188
- logger.warn(`[${operation}] 慢操作警告`, {
189
- ns,
190
- duration,
191
- threshold: slowQueryMs,
192
- filterKeys: Object.keys(filter),
193
- updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators',
194
- updateKeys: isAggregation ? ['[pipeline]'] : Object.keys(update),
195
- pipelineStages: isAggregation ? update.length : undefined,
196
- matchedCount: result.matchedCount,
197
- modifiedCount: result.modifiedCount,
198
- upserted: result.upsertedId ? true : false,
199
- comment: options.comment
200
- });
201
- } else {
202
- logger.debug(`[${operation}] 操作完成`, {
203
- ns,
204
- duration,
205
- updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators',
206
- matchedCount: result.matchedCount,
207
- modifiedCount: result.modifiedCount,
208
- upserted: result.upsertedId ? true : false
209
- });
210
- }
211
-
212
- return result;
213
-
214
- } catch (error) {
215
- // 6. 错误处理
216
- const duration = Date.now() - startTime;
217
-
218
- logger.error(`[${operation}] 操作失败`, {
219
- ns,
220
- duration,
221
- error: error.message,
222
- code: error.code,
223
- filterKeys: Object.keys(filter),
224
- updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators',
225
- updateKeys: isAggregation ? ['[pipeline]'] : Object.keys(update)
226
- });
227
-
228
- // ✨ v1.0.8: 检测聚合管道不支持的错误(MongoDB 4.2+ 才支持)
229
- if (isAggregation &&
230
- (error.message.includes('pipeline') ||
231
- error.message.includes('Unrecognized pipeline stage') ||
232
- error.message.includes('The dollar ($) prefixed field') ||
233
- error.code === 40324 || // MongoDB 错误码:不支持的操作
234
- error.code === 9)) { // MongoDB 错误码:解析错误
235
- throw createError(
236
- ErrorCodes.UNSUPPORTED_OPERATION,
237
- 'MongoDB 4.2+ 才支持聚合管道更新。请升级 MongoDB 版本或使用传统更新操作符',
238
- [{
239
- field: 'update',
240
- message: error.message,
241
- requirement: 'MongoDB 4.2+',
242
- currentError: error.code,
243
- documentation: 'https://www.mongodb.com/docs/manual/tutorial/update-documents-with-aggregation-pipeline/'
244
- }],
245
- error
246
- );
247
- }
248
-
249
- // 识别特定错误类型
250
- if (error.code === 11000) {
251
- // MongoDB 重复键错误(可能在 upsert 时发生)
252
- throw createError(
253
- ErrorCodes.DUPLICATE_KEY,
254
- '批量更新失败:违反唯一性约束',
255
- [{ field: '_id', message: error.message }],
256
- error
257
- );
258
- }
259
-
260
- // 其他错误
261
- throw createError(
262
- ErrorCodes.WRITE_ERROR,
263
- `updateMany 操作失败: ${error.message}`,
264
- null,
265
- error
266
- );
267
- }
268
- };
269
-
270
- return { updateMany };
271
- }
272
-
273
- module.exports = { createUpdateManyOps };
274
-
275
-
@@ -1,273 +0,0 @@
1
- /**
2
- * updateOne 操作实现
3
- * 更新单个匹配的文档
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
9
- const { convertObjectIdStrings, convertUpdateDocument } = require('../../utils/objectid-converter');
10
- const { validateAggregationPipeline, isAggregationPipeline } = require('../common/aggregation-validator');
11
-
12
- /**
13
- * 创建 updateOne 操作
14
- * @param {Object} context - 模块上下文
15
- * @param {Object} context.db - MongoDB 数据库实例
16
- * @param {Object} context.cache - 缓存实例
17
- * @param {Object} context.logger - 日志实例
18
- * @param {Object} context.defaults - 默认配置
19
- * @param {string} context.collection - 集合名称
20
- * @param {string} context.effectiveDbName - 数据库名称
21
- * @param {string} context.instanceId - 实例ID
22
- * @returns {Object} 包含 updateOne 方法的对象
23
- */
24
- function createUpdateOneOps(context) {
25
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
26
-
27
- // 提取集合名称和原生 collection 对象
28
- const collectionName = collection.collectionName;
29
- const nativeCollection = collection;
30
-
31
- /**
32
- * 更新单个文档
33
- * @param {Object} filter - 筛选条件(必需)
34
- * @param {Object} update - 更新操作(必需,使用更新操作符如 $set)
35
- * @param {Object} [options] - 操作选项
36
- * @param {boolean} [options.upsert=false] - 不存在时是否插入
37
- * @param {Object} [options.writeConcern] - 写关注选项
38
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
39
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
40
- * @param {Object} [options.collation] - 排序规则
41
- * @param {Array|Object} [options.arrayFilters] - 数组过滤器
42
- * @param {Object} [options.hint] - 索引提示
43
- * @returns {Promise<Object>} 更新结果 { acknowledged, matchedCount, modifiedCount, upsertedId?, upsertedCount? }
44
- * @throws {Error} 当参数无效时
45
- *
46
- * @example
47
- * const result = await collection("users").updateOne(
48
- * { userId: "user123" },
49
- * { $set: { status: "active", updatedAt: new Date() } }
50
- * );
51
- * console.log("Modified:", result.modifiedCount);
52
- *
53
- * @example
54
- * // 使用 upsert 选项
55
- * const result = await collection("users").updateOne(
56
- * { userId: "user123" },
57
- * { $set: { name: "Alice", age: 25 } },
58
- * { upsert: true }
59
- * );
60
- */
61
- const updateOne = async function updateOne(filter, update, options = {}) {
62
- const startTime = Date.now();
63
-
64
- // 1. 参数验证
65
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
66
- throw createError(
67
- ErrorCodes.INVALID_ARGUMENT,
68
- 'filter 必须是对象类型',
69
- [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
70
- );
71
- }
72
-
73
- if (!update || (typeof update !== 'object' && !Array.isArray(update))) {
74
- throw createError(
75
- ErrorCodes.INVALID_ARGUMENT,
76
- 'update 必须是对象(更新操作符)或数组(聚合管道)',
77
- [{ field: 'update', type: 'object|array.required', message: 'update 必须是更新操作符对象或聚合管道数组' }]
78
- );
79
- }
80
-
81
- // 检测聚合管道模式
82
- const isAggregation = isAggregationPipeline(update);
83
-
84
- if (isAggregation) {
85
- // 验证聚合管道格式
86
- validateAggregationPipeline(update);
87
-
88
- if (logger && logger.debug) {
89
- logger.debug(`[updateOne] 使用聚合管道模式`, {
90
- collection: collectionName,
91
- stagesCount: update.length,
92
- operators: update.map(stage => Object.keys(stage)[0])
93
- });
94
- }
95
- } else {
96
- // 验证 update 包含更新操作符(防止整体替换)
97
- const updateKeys = Object.keys(update);
98
-
99
- // 检查空对象
100
- if (updateKeys.length === 0) {
101
- throw createError(
102
- ErrorCodes.INVALID_ARGUMENT,
103
- 'update 不能为空对象',
104
- [{ field: 'update', type: 'object.empty', message: 'update 必须包含至少一个更新操作符,如 $set、$inc、$push 等' }]
105
- );
106
- }
107
-
108
- // 检查是否包含操作符
109
- if (!updateKeys.some(key => key.startsWith('$'))) {
110
- throw createError(
111
- ErrorCodes.INVALID_ARGUMENT,
112
- 'update 必须使用更新操作符(如 $set, $inc 等)',
113
- [{ field: 'update', type: 'object.invalid', message: '请使用 $set, $inc, $push 等更新操作符,或使用 replaceOne 进行整体替换' }]
114
- );
115
- }
116
- }
117
-
118
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
119
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
120
- logger: context.logger,
121
- excludeFields: context.autoConvertConfig?.excludeFields,
122
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
123
- maxDepth: context.autoConvertConfig?.maxDepth
124
- });
125
-
126
- // ✅ v1.0.8: 聚合管道不转换 ObjectId(保持原样)
127
- const convertedUpdate = isAggregation
128
- ? update // 聚合管道保持原样
129
- : convertUpdateDocument(update, {
130
- logger: context.logger,
131
- excludeFields: context.autoConvertConfig?.excludeFields,
132
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
133
- maxDepth: context.autoConvertConfig?.maxDepth
134
- });
135
-
136
- // 2. 构建操作上下文
137
- const operation = 'updateOne';
138
- const ns = `${databaseName}.${collectionName}`;
139
-
140
- try {
141
- // 3. 执行更新操作
142
- const result = await nativeCollection.updateOne(convertedFilter, convertedUpdate, options);
143
-
144
- // 4. 自动失效缓存
145
- // ✅ v1.1.6: 修复 upsert 场景的缓存失效问题 - 检查 modifiedCount 或 upsertedId
146
- if (cache && (result.modifiedCount > 0 || result.upsertedId)) {
147
- try {
148
- // 🆕 v1.1.6: 解析精准失效配置
149
- const instanceAuto = context.cacheAutoInvalidate || false;
150
- const queryAuto = options.autoInvalidate;
151
- const shouldAuto = queryAuto !== undefined ? queryAuto : instanceAuto;
152
-
153
- if (shouldAuto) {
154
- // 精准失效:updateOne 使用 filter 来匹配缓存
155
- const CacheInvalidationEngine = require('../../cache-invalidation');
156
-
157
- const deleted = await CacheInvalidationEngine.invalidatePrecise(cache, {
158
- instanceId,
159
- type: 'mongodb',
160
- db: databaseName,
161
- collection: collectionName,
162
- document: convertedFilter, // 使用 filter 来匹配
163
- operation: result.upsertedId ? 'upsert' : 'updateOne'
164
- });
165
-
166
- if (deleted > 0) {
167
- logger.debug(`[${operation}] 精准失效缓存: ${databaseName}.${collectionName}, 删除 ${deleted} 个缓存键${result.upsertedId ? ' (upsert)' : ''}`);
168
- }
169
- } else {
170
- logger.debug(`[${operation}] 跳过自动失效(autoInvalidate=false)`);
171
- }
172
- } catch (cacheErr) {
173
- // 缓存失效失败不影响写操作
174
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, {
175
- ns: `${databaseName}.${collectionName}`,
176
- error: cacheErr,
177
- upserted: !!result.upsertedId
178
- });
179
- }
180
- }
181
-
182
- // 5. 记录慢操作日志
183
- const duration = Date.now() - startTime;
184
- const slowQueryMs = defaults.slowQueryMs || 1000;
185
- if (duration > slowQueryMs) {
186
- logger.warn(`[${operation}] 慢操作警告`, {
187
- ns,
188
- duration,
189
- threshold: slowQueryMs,
190
- filterKeys: Object.keys(filter),
191
- updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators',
192
- updateKeys: isAggregation ? ['[pipeline]'] : Object.keys(update),
193
- pipelineStages: isAggregation ? update.length : undefined,
194
- matchedCount: result.matchedCount,
195
- modifiedCount: result.modifiedCount,
196
- upserted: result.upsertedId ? true : false,
197
- comment: options.comment
198
- });
199
- } else {
200
- logger.debug(`[${operation}] 操作完成`, {
201
- ns,
202
- duration,
203
- updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators',
204
- matchedCount: result.matchedCount,
205
- modifiedCount: result.modifiedCount,
206
- upserted: result.upsertedId ? true : false
207
- });
208
- }
209
-
210
- return result;
211
-
212
- } catch (error) {
213
- // 6. 错误处理
214
- const duration = Date.now() - startTime;
215
-
216
- logger.error(`[${operation}] 操作失败`, {
217
- ns,
218
- duration,
219
- error: error.message,
220
- code: error.code,
221
- filterKeys: Object.keys(filter),
222
- updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators',
223
- updateKeys: isAggregation ? ['[pipeline]'] : Object.keys(update)
224
- });
225
-
226
- // ✨ v1.0.8: 检测聚合管道不支持的错误(MongoDB 4.2+ 才支持)
227
- if (isAggregation &&
228
- (error.message.includes('pipeline') ||
229
- error.message.includes('Unrecognized pipeline stage') ||
230
- error.message.includes('The dollar ($) prefixed field') ||
231
- error.code === 40324 || // MongoDB 错误码:不支持的操作
232
- error.code === 9)) { // MongoDB 错误码:解析错误
233
- throw createError(
234
- ErrorCodes.UNSUPPORTED_OPERATION,
235
- 'MongoDB 4.2+ 才支持聚合管道更新。请升级 MongoDB 版本或使用传统更新操作符',
236
- [{
237
- field: 'update',
238
- message: error.message,
239
- requirement: 'MongoDB 4.2+',
240
- currentError: error.code,
241
- documentation: 'https://www.mongodb.com/docs/manual/tutorial/update-documents-with-aggregation-pipeline/'
242
- }],
243
- error
244
- );
245
- }
246
-
247
- // 识别特定错误类型
248
- if (error.code === 11000) {
249
- // MongoDB 重复键错误(可能在 upsert 时发生)
250
- throw createError(
251
- ErrorCodes.DUPLICATE_KEY,
252
- '更新失败:违反唯一性约束',
253
- [{ field: '_id', message: error.message }],
254
- error
255
- );
256
- }
257
-
258
- // 其他错误
259
- throw createError(
260
- ErrorCodes.WRITE_ERROR,
261
- `updateOne 操作失败: ${error.message}`,
262
- null,
263
- error
264
- );
265
- }
266
- };
267
-
268
- return { updateOne };
269
- }
270
-
271
- module.exports = { createUpdateOneOps };
272
-
273
-