monsqlize 1.3.1 → 2.0.1

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 (114) hide show
  1. package/CHANGELOG.md +506 -235
  2. package/LICENSE +201 -21
  3. package/README.md +542 -928
  4. package/changelogs/README.md +163 -0
  5. package/changelogs/v2.0.0.md +222 -0
  6. package/changelogs/v2.0.1.md +39 -0
  7. package/dist/cjs/index.cjs +10788 -0
  8. package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
  9. package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
  10. package/dist/cjs/transaction/Transaction.cjs +158 -0
  11. package/dist/cjs/transaction/TransactionManager.cjs +298 -0
  12. package/dist/esm/index.mjs +10838 -0
  13. package/dist/types/base.d.ts +81 -0
  14. package/dist/types/collection.d.ts +1031 -0
  15. package/dist/types/expression.d.ts +115 -0
  16. package/dist/types/index.d.ts +23 -0
  17. package/dist/types/lock.d.ts +74 -0
  18. package/dist/types/model.d.ts +530 -0
  19. package/dist/types/mongodb.d.ts +49 -0
  20. package/dist/types/monsqlize.d.ts +491 -0
  21. package/dist/types/pool.d.ts +84 -0
  22. package/dist/types/runtime.d.ts +362 -0
  23. package/dist/types/saga.d.ts +143 -0
  24. package/dist/types/slow-query-log.d.ts +126 -0
  25. package/dist/types/sync.d.ts +103 -0
  26. package/dist/types/transaction.d.ts +132 -0
  27. package/package.json +120 -117
  28. package/index.d.ts +0 -1289
  29. package/lib/cache.js +0 -491
  30. package/lib/common/cursor.js +0 -58
  31. package/lib/common/docs-urls.js +0 -72
  32. package/lib/common/index-options.js +0 -222
  33. package/lib/common/log.js +0 -60
  34. package/lib/common/namespace.js +0 -21
  35. package/lib/common/normalize.js +0 -33
  36. package/lib/common/page-result.js +0 -42
  37. package/lib/common/runner.js +0 -56
  38. package/lib/common/server-features.js +0 -231
  39. package/lib/common/shape-builders.js +0 -26
  40. package/lib/common/validation.js +0 -112
  41. package/lib/connect.js +0 -76
  42. package/lib/constants.js +0 -54
  43. package/lib/count-queue.js +0 -187
  44. package/lib/distributed-cache-invalidator.js +0 -259
  45. package/lib/errors.js +0 -167
  46. package/lib/index.js +0 -461
  47. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -211
  48. package/lib/infrastructure/ssh-tunnel.js +0 -40
  49. package/lib/infrastructure/uri-parser.js +0 -35
  50. package/lib/lock/Lock.js +0 -66
  51. package/lib/lock/errors.js +0 -27
  52. package/lib/lock/index.js +0 -12
  53. package/lib/logger.js +0 -224
  54. package/lib/model/examples/test.js +0 -114
  55. package/lib/mongodb/common/accessor-helpers.js +0 -58
  56. package/lib/mongodb/common/agg-pipeline.js +0 -32
  57. package/lib/mongodb/common/iid.js +0 -27
  58. package/lib/mongodb/common/lexicographic-expr.js +0 -52
  59. package/lib/mongodb/common/shape.js +0 -31
  60. package/lib/mongodb/common/sort.js +0 -38
  61. package/lib/mongodb/common/transaction-aware.js +0 -24
  62. package/lib/mongodb/connect.js +0 -233
  63. package/lib/mongodb/index.js +0 -591
  64. package/lib/mongodb/management/admin-ops.js +0 -199
  65. package/lib/mongodb/management/bookmark-ops.js +0 -166
  66. package/lib/mongodb/management/cache-ops.js +0 -49
  67. package/lib/mongodb/management/collection-ops.js +0 -386
  68. package/lib/mongodb/management/database-ops.js +0 -201
  69. package/lib/mongodb/management/index-ops.js +0 -474
  70. package/lib/mongodb/management/index.js +0 -16
  71. package/lib/mongodb/management/namespace.js +0 -30
  72. package/lib/mongodb/management/validation-ops.js +0 -267
  73. package/lib/mongodb/queries/aggregate.js +0 -142
  74. package/lib/mongodb/queries/chain.js +0 -630
  75. package/lib/mongodb/queries/count.js +0 -98
  76. package/lib/mongodb/queries/distinct.js +0 -77
  77. package/lib/mongodb/queries/find-and-count.js +0 -192
  78. package/lib/mongodb/queries/find-by-ids.js +0 -235
  79. package/lib/mongodb/queries/find-one-by-id.js +0 -170
  80. package/lib/mongodb/queries/find-one.js +0 -70
  81. package/lib/mongodb/queries/find-page.js +0 -577
  82. package/lib/mongodb/queries/find.js +0 -170
  83. package/lib/mongodb/queries/index.js +0 -50
  84. package/lib/mongodb/queries/watch.js +0 -537
  85. package/lib/mongodb/writes/delete-many.js +0 -190
  86. package/lib/mongodb/writes/delete-one.js +0 -182
  87. package/lib/mongodb/writes/find-one-and-delete.js +0 -202
  88. package/lib/mongodb/writes/find-one-and-replace.js +0 -238
  89. package/lib/mongodb/writes/find-one-and-update.js +0 -239
  90. package/lib/mongodb/writes/increment-one.js +0 -252
  91. package/lib/mongodb/writes/index.js +0 -41
  92. package/lib/mongodb/writes/insert-batch.js +0 -507
  93. package/lib/mongodb/writes/insert-many.js +0 -227
  94. package/lib/mongodb/writes/insert-one.js +0 -180
  95. package/lib/mongodb/writes/replace-one.js +0 -215
  96. package/lib/mongodb/writes/result-handler.js +0 -236
  97. package/lib/mongodb/writes/update-many.js +0 -221
  98. package/lib/mongodb/writes/update-one.js +0 -223
  99. package/lib/mongodb/writes/upsert-one.js +0 -206
  100. package/lib/multi-level-cache.js +0 -189
  101. package/lib/operators.js +0 -330
  102. package/lib/redis-cache-adapter.js +0 -237
  103. package/lib/slow-query-log/base-storage.js +0 -69
  104. package/lib/slow-query-log/batch-queue.js +0 -96
  105. package/lib/slow-query-log/config-manager.js +0 -195
  106. package/lib/slow-query-log/index.js +0 -237
  107. package/lib/slow-query-log/mongodb-storage.js +0 -323
  108. package/lib/slow-query-log/query-hash.js +0 -38
  109. package/lib/transaction/CacheLockManager.js +0 -161
  110. package/lib/transaction/DistributedCacheLockManager.js +0 -474
  111. package/lib/transaction/Transaction.js +0 -314
  112. package/lib/transaction/TransactionManager.js +0 -266
  113. package/lib/transaction/index.js +0 -10
  114. package/lib/utils/objectid-converter.js +0 -566
@@ -1,238 +0,0 @@
1
- /**
2
- * findOneAndReplace 操作实现
3
- * 原子地查找并替换单个文档
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { handleFindOneAndResult, wasDocumentModified } = require('./result-handler');
9
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
10
- const { convertObjectIdStrings } = require('../../utils/objectid-converter');
11
-
12
- /**
13
- * 创建 findOneAndReplace 操作
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} 包含 findOneAndReplace 方法的对象
23
- */
24
- function createFindOneAndReplaceOps(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} replacement - 替换文档(必需,不能包含更新操作符)
35
- * @param {Object} [options] - 操作选项
36
- * @param {Object} [options.projection] - 字段投影
37
- * @param {Object} [options.sort] - 排序条件
38
- * @param {boolean} [options.upsert=false] - 不存在时是否插入
39
- * @param {string} [options.returnDocument="before"] - 返回替换前("before")或替换后("after")的文档
40
- * @param {number} [options.maxTimeMS] - 最大执行时间
41
- * @param {Object} [options.writeConcern] - 写关注选项
42
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
43
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
44
- * @param {Object} [options.collation] - 排序规则
45
- * @param {Object} [options.hint] - 索引提示
46
- * @param {boolean} [options.includeResultMetadata=false] - 是否包含完整结果元数据
47
- * @returns {Promise<Object|null>} 返回文档或 null(未找到);includeResultMetadata=true 时返回 { value, ok, lastErrorObject }
48
- * @throws {Error} 当参数无效时
49
- *
50
- * @example
51
- * // 返回替换前的文档(默认)
52
- * const oldDoc = await collection("users").findOneAndReplace(
53
- * { userId: "user123" },
54
- * { userId: "user123", name: "Alice", age: 25, status: "active" }
55
- * );
56
- * console.log("Old doc:", oldDoc);
57
- *
58
- * @example
59
- * // 返回替换后的文档
60
- * const newDoc = await collection("users").findOneAndReplace(
61
- * { userId: "user123" },
62
- * { userId: "user123", name: "Alice", age: 26 },
63
- * { returnDocument: "after" }
64
- * );
65
- * console.log("New doc:", newDoc);
66
- *
67
- * @example
68
- * // 使用 upsert
69
- * const doc = await collection("config").findOneAndReplace(
70
- * { key: "theme" },
71
- * { key: "theme", value: "dark", updatedAt: new Date() },
72
- * { upsert: true, returnDocument: "after" }
73
- * );
74
- */
75
- const findOneAndReplace = async function findOneAndReplace(filter, replacement, options = {}) {
76
- const startTime = Date.now();
77
-
78
- // 1. 参数验证
79
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
80
- throw createError(
81
- ErrorCodes.INVALID_ARGUMENT,
82
- 'filter 必须是对象类型',
83
- [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
84
- );
85
- }
86
-
87
- if (!replacement || typeof replacement !== 'object' || Array.isArray(replacement)) {
88
- throw createError(
89
- ErrorCodes.INVALID_ARGUMENT,
90
- 'replacement 必须是对象类型',
91
- [{ field: 'replacement', type: 'object.required', message: 'replacement 是必需参数且必须是对象' }]
92
- );
93
- }
94
-
95
- // 验证 replacement 不包含更新操作符
96
- const replacementKeys = Object.keys(replacement);
97
- if (replacementKeys.some(key => key.startsWith('$'))) {
98
- throw createError(
99
- ErrorCodes.INVALID_ARGUMENT,
100
- 'replacement 不能包含更新操作符(如 $set, $inc 等)',
101
- [{ field: 'replacement', type: 'object.invalid', message: 'findOneAndReplace 用于完整替换文档,请使用 findOneAndUpdate 进行部分更新' }]
102
- );
103
- }
104
-
105
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
106
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
107
- logger: context.logger,
108
- excludeFields: context.autoConvertConfig?.excludeFields,
109
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
110
- maxDepth: context.autoConvertConfig?.maxDepth
111
- });
112
-
113
- const convertedReplacement = convertObjectIdStrings(replacement, 'document', 0, new WeakSet(), {
114
- logger: context.logger,
115
- excludeFields: context.autoConvertConfig?.excludeFields,
116
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
117
- maxDepth: context.autoConvertConfig?.maxDepth
118
- });
119
-
120
- // 2. 构建操作上下文
121
- const operation = 'findOneAndReplace';
122
- const ns = `${databaseName}.${collectionName}`;
123
-
124
- try {
125
- // 3. 执行查找并替换操作
126
- // MongoDB 驱动 6.x: 默认返回文档,需要 includeResultMetadata=true 获取完整元数据
127
- const driverOptions = { ...options, includeResultMetadata: true };
128
- const result = await nativeCollection.findOneAndReplace(convertedFilter, convertedReplacement, driverOptions);
129
-
130
- // 4. 自动失效缓存(如果有文档被修改)
131
- // 使用安全的修改判断函数
132
- const wasModified = wasDocumentModified(result);
133
- if (cache && wasModified) {
134
- try {
135
- const ns = {
136
- iid: instanceId,
137
- type: 'mongodb',
138
- db: databaseName,
139
- collection: collectionName
140
- };
141
- const pattern = CacheFactory.buildNamespacePattern(ns);
142
-
143
- // 检查是否在事务中
144
- if (isInTransaction(options)) {
145
- // 事务中:调用 Transaction 的 recordInvalidation 方法
146
- const tx = getTransactionFromSession(options.session);
147
- if (tx && typeof tx.recordInvalidation === 'function') {
148
- // 🚀 传递 metadata 支持文档级别锁
149
- await tx.recordInvalidation(pattern, {
150
- operation: 'write',
151
- query: filter,
152
- collection: collectionName
153
- });
154
- logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
155
- } else {
156
- const deleted = await cache.delPattern(pattern);
157
- if (deleted > 0) {
158
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
159
- }
160
- }
161
- } else {
162
- // 非事务:直接失效缓存
163
- const deleted = await cache.delPattern(pattern);
164
- if (deleted > 0) {
165
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
166
- }
167
- }
168
- } catch (cacheErr) {
169
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
170
- }
171
- }
172
-
173
- // 5. 记录慢操作日志
174
- const duration = Date.now() - startTime;
175
- const slowQueryMs = defaults.slowQueryMs || 1000;
176
- if (duration > slowQueryMs) {
177
- logger.warn(`[${operation}] 慢操作警告`, {
178
- ns,
179
- duration,
180
- threshold: slowQueryMs,
181
- filterKeys: Object.keys(filter),
182
- replacementKeys: Object.keys(replacement),
183
- found: result && result.value !== null,
184
- upserted: result?.lastErrorObject?.upserted ? true : false,
185
- returnDocument: options.returnDocument || 'before',
186
- comment: options.comment
187
- });
188
- } else {
189
- logger.debug(`[${operation}] 操作完成`, {
190
- ns,
191
- duration,
192
- found: result && result.value !== null,
193
- upserted: result?.lastErrorObject?.upserted ? true : false,
194
- returnDocument: options.returnDocument || 'before'
195
- });
196
- }
197
-
198
- // 6. 返回结果(使用统一的返回值处理函数)
199
- return handleFindOneAndResult(result, options, logger);
200
-
201
- } catch (error) {
202
- // 7. 错误处理
203
- const duration = Date.now() - startTime;
204
-
205
- logger.error(`[${operation}] 操作失败`, {
206
- ns,
207
- duration,
208
- error: error.message,
209
- code: error.code,
210
- filterKeys: Object.keys(filter),
211
- replacementKeys: Object.keys(replacement)
212
- });
213
-
214
- // 识别特定错误类型
215
- if (error.code === 11000) {
216
- throw createError(
217
- ErrorCodes.DUPLICATE_KEY,
218
- '查找并替换失败:违反唯一性约束',
219
- [{ field: '_id', message: error.message }],
220
- error
221
- );
222
- }
223
-
224
- // 其他错误
225
- throw createError(
226
- ErrorCodes.WRITE_ERROR,
227
- `findOneAndReplace 操作失败: ${error.message}`,
228
- null,
229
- error
230
- );
231
- }
232
- };
233
-
234
- return { findOneAndReplace };
235
- }
236
-
237
- module.exports = { createFindOneAndReplaceOps };
238
-
@@ -1,239 +0,0 @@
1
- /**
2
- * findOneAndUpdate 操作实现
3
- * 原子地查找并更新单个文档
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { handleFindOneAndResult, wasDocumentModified } = require('./result-handler');
9
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
10
- const { convertObjectIdStrings, convertUpdateDocument } = require('../../utils/objectid-converter');
11
-
12
- /**
13
- * 创建 findOneAndUpdate 操作
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} 包含 findOneAndUpdate 方法的对象
23
- */
24
- function createFindOneAndUpdateOps(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 {Object} [options.projection] - 字段投影
37
- * @param {Object} [options.sort] - 排序条件
38
- * @param {boolean} [options.upsert=false] - 不存在时是否插入
39
- * @param {string} [options.returnDocument="before"] - 返回更新前("before")或更新后("after")的文档
40
- * @param {number} [options.maxTimeMS] - 最大执行时间
41
- * @param {Object} [options.writeConcern] - 写关注选项
42
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
43
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
44
- * @param {Object} [options.collation] - 排序规则
45
- * @param {Array|Object} [options.arrayFilters] - 数组过滤器
46
- * @param {Object} [options.hint] - 索引提示
47
- * @param {boolean} [options.includeResultMetadata=false] - 是否包含完整结果元数据
48
- * @returns {Promise<Object|null>} 返回文档或 null(未找到);includeResultMetadata=true 时返回 { value, ok, lastErrorObject }
49
- * @throws {Error} 当参数无效时
50
- *
51
- * @example
52
- * // 返回更新前的文档(默认)
53
- * const oldDoc = await collection("users").findOneAndUpdate(
54
- * { userId: "user123" },
55
- * { $set: { status: "active" } }
56
- * );
57
- * console.log("Old status:", oldDoc?.status);
58
- *
59
- * @example
60
- * // 返回更新后的文档
61
- * const newDoc = await collection("users").findOneAndUpdate(
62
- * { userId: "user123" },
63
- * { $inc: { loginCount: 1 } },
64
- * { returnDocument: "after" }
65
- * );
66
- * console.log("New login count:", newDoc?.loginCount);
67
- *
68
- * @example
69
- * // 使用 upsert + 排序
70
- * const doc = await collection("counters").findOneAndUpdate(
71
- * { name: "orderCounter" },
72
- * { $inc: { value: 1 } },
73
- * { upsert: true, returnDocument: "after", sort: { _id: -1 } }
74
- * );
75
- */
76
- const findOneAndUpdate = async function findOneAndUpdate(filter, update, options = {}) {
77
- const startTime = Date.now();
78
-
79
- // 1. 参数验证
80
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
81
- throw createError(
82
- ErrorCodes.INVALID_ARGUMENT,
83
- 'filter 必须是对象类型',
84
- [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
85
- );
86
- }
87
-
88
- if (!update || typeof update !== 'object' || Array.isArray(update)) {
89
- throw createError(
90
- ErrorCodes.INVALID_ARGUMENT,
91
- 'update 必须是对象类型',
92
- [{ field: 'update', type: 'object.required', message: 'update 是必需参数且必须是对象' }]
93
- );
94
- }
95
-
96
- // 验证 update 包含更新操作符
97
- const updateKeys = Object.keys(update);
98
- if (updateKeys.length > 0 && !updateKeys.some(key => key.startsWith('$'))) {
99
- throw createError(
100
- ErrorCodes.INVALID_ARGUMENT,
101
- 'update 必须使用更新操作符(如 $set, $inc 等)',
102
- [{ field: 'update', type: 'object.invalid', message: '请使用 $set, $inc, $push 等更新操作符,或使用 findOneAndReplace 进行整体替换' }]
103
- );
104
- }
105
-
106
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
107
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
108
- logger: context.logger,
109
- excludeFields: context.autoConvertConfig?.excludeFields,
110
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
111
- maxDepth: context.autoConvertConfig?.maxDepth
112
- });
113
-
114
- const convertedUpdate = convertUpdateDocument(update, {
115
- logger: context.logger,
116
- excludeFields: context.autoConvertConfig?.excludeFields,
117
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
118
- maxDepth: context.autoConvertConfig?.maxDepth
119
- });
120
-
121
- // 2. 构建操作上下文
122
- const operation = 'findOneAndUpdate';
123
- const ns = `${databaseName}.${collectionName}`;
124
-
125
- try {
126
- // 3. 执行查找并更新操作
127
- // MongoDB 驱动 6.x: 默认返回文档,需要 includeResultMetadata=true 获取完整元数据
128
- const driverOptions = { ...options, includeResultMetadata: true };
129
- const result = await nativeCollection.findOneAndUpdate(convertedFilter, convertedUpdate, driverOptions);
130
-
131
- // 4. 自动失效缓存(如果有文档被修改)
132
- // 使用安全的修改判断函数
133
- const wasModified = wasDocumentModified(result);
134
- if (cache && wasModified) {
135
- try {
136
- const ns = {
137
- iid: instanceId,
138
- type: 'mongodb',
139
- db: databaseName,
140
- collection: collectionName
141
- };
142
- const pattern = CacheFactory.buildNamespacePattern(ns);
143
-
144
- // 检查是否在事务中
145
- if (isInTransaction(options)) {
146
- // 事务中:调用 Transaction 的 recordInvalidation 方法
147
- const tx = getTransactionFromSession(options.session);
148
- if (tx && typeof tx.recordInvalidation === 'function') {
149
- // 🚀 传递 metadata 支持文档级别锁
150
- await tx.recordInvalidation(pattern, {
151
- operation: 'write',
152
- query: filter,
153
- collection: collectionName
154
- });
155
- logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
156
- } else {
157
- const deleted = await cache.delPattern(pattern);
158
- if (deleted > 0) {
159
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
160
- }
161
- }
162
- } else {
163
- // 非事务:直接失效缓存
164
- const deleted = await cache.delPattern(pattern);
165
- if (deleted > 0) {
166
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
167
- }
168
- }
169
- } catch (cacheErr) {
170
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
171
- }
172
- }
173
-
174
- // 5. 记录慢操作日志
175
- const duration = Date.now() - startTime;
176
- const slowQueryMs = defaults.slowQueryMs || 1000;
177
- if (duration > slowQueryMs) {
178
- logger.warn(`[${operation}] 慢操作警告`, {
179
- ns,
180
- duration,
181
- threshold: slowQueryMs,
182
- filterKeys: Object.keys(filter),
183
- updateKeys: Object.keys(update),
184
- found: result && result.value !== null,
185
- upserted: result?.lastErrorObject?.upserted ? true : false,
186
- returnDocument: options.returnDocument || 'before',
187
- comment: options.comment
188
- });
189
- } else {
190
- logger.debug(`[${operation}] 操作完成`, {
191
- ns,
192
- duration,
193
- found: result && result.value !== null,
194
- upserted: result?.lastErrorObject?.upserted ? true : false,
195
- returnDocument: options.returnDocument || 'before'
196
- });
197
- }
198
-
199
- // 6. 返回结果(使用统一的返回值处理函数)
200
- return handleFindOneAndResult(result, options, logger);
201
-
202
- } catch (error) {
203
- // 7. 错误处理
204
- const duration = Date.now() - startTime;
205
-
206
- logger.error(`[${operation}] 操作失败`, {
207
- ns,
208
- duration,
209
- error: error.message,
210
- code: error.code,
211
- filterKeys: Object.keys(filter),
212
- updateKeys: Object.keys(update)
213
- });
214
-
215
- // 识别特定错误类型
216
- if (error.code === 11000) {
217
- throw createError(
218
- ErrorCodes.DUPLICATE_KEY,
219
- '查找并更新失败:违反唯一性约束',
220
- [{ field: '_id', message: error.message }],
221
- error
222
- );
223
- }
224
-
225
- // 其他错误
226
- throw createError(
227
- ErrorCodes.WRITE_ERROR,
228
- `findOneAndUpdate 操作失败: ${error.message}`,
229
- null,
230
- error
231
- );
232
- }
233
- };
234
-
235
- return { findOneAndUpdate };
236
- }
237
-
238
- module.exports = { createFindOneAndUpdateOps };
239
-