monsqlize 1.0.1 → 1.0.5

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 (66) hide show
  1. package/CHANGELOG.md +204 -2464
  2. package/README.md +735 -1198
  3. package/index.d.ts +942 -18
  4. package/lib/cache.js +8 -8
  5. package/lib/common/validation.js +64 -1
  6. package/lib/connect.js +3 -3
  7. package/lib/errors.js +10 -0
  8. package/lib/index.js +173 -9
  9. package/lib/infrastructure/ssh-tunnel-ssh2.js +211 -0
  10. package/lib/infrastructure/ssh-tunnel.js +40 -0
  11. package/lib/infrastructure/uri-parser.js +35 -0
  12. package/lib/lock/Lock.js +66 -0
  13. package/lib/lock/errors.js +27 -0
  14. package/lib/lock/index.js +12 -0
  15. package/lib/logger.js +1 -1
  16. package/lib/model/examples/test.js +225 -29
  17. package/lib/model/features/soft-delete.js +348 -0
  18. package/lib/model/features/version.js +156 -0
  19. package/lib/model/index.js +756 -0
  20. package/lib/mongodb/common/accessor-helpers.js +17 -3
  21. package/lib/mongodb/connect.js +68 -13
  22. package/lib/mongodb/index.js +153 -6
  23. package/lib/mongodb/management/collection-ops.js +4 -4
  24. package/lib/mongodb/management/index-ops.js +18 -18
  25. package/lib/mongodb/management/validation-ops.js +3 -3
  26. package/lib/mongodb/queries/aggregate.js +14 -5
  27. package/lib/mongodb/queries/chain.js +52 -45
  28. package/lib/mongodb/queries/count.js +16 -6
  29. package/lib/mongodb/queries/distinct.js +15 -6
  30. package/lib/mongodb/queries/find-and-count.js +22 -13
  31. package/lib/mongodb/queries/find-by-ids.js +5 -5
  32. package/lib/mongodb/queries/find-one-by-id.js +1 -1
  33. package/lib/mongodb/queries/find-one.js +12 -3
  34. package/lib/mongodb/queries/find-page.js +12 -0
  35. package/lib/mongodb/queries/find.js +15 -6
  36. package/lib/mongodb/queries/watch.js +11 -2
  37. package/lib/mongodb/writes/common/batch-retry.js +64 -0
  38. package/lib/mongodb/writes/delete-batch.js +322 -0
  39. package/lib/mongodb/writes/delete-many.js +20 -11
  40. package/lib/mongodb/writes/delete-one.js +18 -9
  41. package/lib/mongodb/writes/find-one-and-delete.js +19 -10
  42. package/lib/mongodb/writes/find-one-and-replace.js +36 -20
  43. package/lib/mongodb/writes/find-one-and-update.js +36 -20
  44. package/lib/mongodb/writes/increment-one.js +22 -7
  45. package/lib/mongodb/writes/index.js +17 -13
  46. package/lib/mongodb/writes/insert-batch.js +46 -37
  47. package/lib/mongodb/writes/insert-many.js +22 -13
  48. package/lib/mongodb/writes/insert-one.js +18 -9
  49. package/lib/mongodb/writes/replace-one.js +33 -17
  50. package/lib/mongodb/writes/result-handler.js +14 -14
  51. package/lib/mongodb/writes/update-batch.js +358 -0
  52. package/lib/mongodb/writes/update-many.js +34 -18
  53. package/lib/mongodb/writes/update-one.js +33 -17
  54. package/lib/mongodb/writes/upsert-one.js +25 -9
  55. package/lib/operators.js +1 -1
  56. package/lib/redis-cache-adapter.js +3 -3
  57. package/lib/slow-query-log/base-storage.js +69 -0
  58. package/lib/slow-query-log/batch-queue.js +96 -0
  59. package/lib/slow-query-log/config-manager.js +195 -0
  60. package/lib/slow-query-log/index.js +237 -0
  61. package/lib/slow-query-log/mongodb-storage.js +323 -0
  62. package/lib/slow-query-log/query-hash.js +38 -0
  63. package/lib/transaction/DistributedCacheLockManager.js +240 -5
  64. package/lib/transaction/Transaction.js +1 -1
  65. package/lib/utils/objectid-converter.js +566 -0
  66. package/package.json +18 -6
@@ -11,6 +11,7 @@ const { decodeCursor } = require('../../common/cursor');
11
11
  const { validateLimitAfterBefore, assertCursorSortCompatible } = require('../../common/validation');
12
12
  const { makePageResult } = require('../../common/page-result');
13
13
  const { normalizeSort } = require('../../common/normalize');
14
+ const { convertObjectIdStrings } = require('../../utils/objectid-converter');
14
15
 
15
16
  // —— Count 队列支持(高并发控制)——
16
17
  let countQueue = null;
@@ -213,6 +214,17 @@ function createFindPage(ctx) {
213
214
 
214
215
  return async function findPage(options = {}) {
215
216
  const startTime = Date.now(); // 记录开始时间
217
+
218
+ // ✅ v1.3.0: 自动转换 ObjectId 字符串
219
+ if (options.query) {
220
+ options.query = convertObjectIdStrings(options.query, 'filter', 0, new WeakSet(), {
221
+ logger: ctx.logger,
222
+ excludeFields: ctx.autoConvertConfig?.excludeFields,
223
+ customFieldPatterns: ctx.autoConvertConfig?.customFieldPatterns,
224
+ maxDepth: ctx.autoConvertConfig?.maxDepth
225
+ });
226
+ }
227
+
216
228
  const MAX_LIMIT = defaults?.findPageMaxLimit ?? 500;
217
229
  // 基础校验:limit + after/before 互斥
218
230
  validateLimitAfterBefore(options, { maxLimit: MAX_LIMIT });
@@ -5,6 +5,7 @@
5
5
 
6
6
  const { normalizeProjection, normalizeSort } = require('../../common/normalize');
7
7
  const { FindChain } = require('./chain');
8
+ const { convertObjectIdStrings } = require('../../utils/objectid-converter');
8
9
 
9
10
  /**
10
11
  * 创建 find 查询操作
@@ -51,12 +52,20 @@ function createFindOps(context) {
51
52
  * @returns {Promise<Array>|ReadableStream|FindChain} 记录数组或可读流(当 stream: true 时);当 explain=true 时返回执行计划;默认返回 FindChain 实例支持链式调用
52
53
  */
53
54
  find: (query = {}, options = {}) => {
55
+ // ✅ v1.3.0: 自动转换 ObjectId 字符串
56
+ const convertedQuery = convertObjectIdStrings(query, 'query', 0, new WeakSet(), {
57
+ logger: context.logger,
58
+ excludeFields: context.autoConvertConfig?.excludeFields,
59
+ customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
60
+ maxDepth: context.autoConvertConfig?.maxDepth
61
+ });
62
+
54
63
  // 如果没有提供 options 或 options 为空对象,返回 FindChain 以支持完整的链式调用
55
64
  const hasOptions = options && Object.keys(options).length > 0;
56
65
 
57
66
  if (!hasOptions) {
58
67
  // 返回 FindChain 实例,支持 .limit().skip().sort() 等链式调用
59
- return new FindChain(context, query, {});
68
+ return new FindChain(context, convertedQuery, {});
60
69
  }
61
70
 
62
71
  // 如果提供了 options,执行原有逻辑(向后兼容)
@@ -81,13 +90,13 @@ function createFindOps(context) {
81
90
  // 如果启用 explain,直接返回执行计划(不缓存)
82
91
  if (explain) {
83
92
  const verbosity = typeof explain === 'string' ? explain : 'queryPlanner';
84
- const cursor = collection.find(query, driverOpts);
93
+ const cursor = collection.find(convertedQuery, driverOpts);
85
94
  return cursor.explain(verbosity);
86
95
  }
87
96
 
88
97
  // 如果启用流式返回,直接返回 MongoDB 游标流
89
98
  if (stream) {
90
- const cursor = collection.find(query, driverOpts);
99
+ const cursor = collection.find(convertedQuery, driverOpts);
91
100
  const readableStream = cursor.stream();
92
101
 
93
102
  // 添加慢查询日志支持
@@ -127,13 +136,13 @@ function createFindOps(context) {
127
136
  // 执行查询的 Promise
128
137
  const resultPromise = run(
129
138
  'find',
130
- { query, ...options },
131
- async () => collection.find(query, driverOpts).toArray()
139
+ { query: convertedQuery, ...options },
140
+ async () => collection.find(convertedQuery, driverOpts).toArray()
132
141
  );
133
142
 
134
143
  // 添加 explain 方法支持链式调用(与原生 MongoDB 一致)
135
144
  resultPromise.explain = async (verbosity = 'queryPlanner') => {
136
- const cursor = collection.find(query, driverOpts);
145
+ const cursor = collection.find(convertedQuery, driverOpts);
137
146
  return cursor.explain(verbosity);
138
147
  };
139
148
 
@@ -488,6 +488,15 @@ function createWatchOps(context) {
488
488
  throw new Error('pipeline must be an array');
489
489
  }
490
490
 
491
+ // ✅ v1.3.0: 自动转换 ObjectId 字符串
492
+ const { convertAggregationPipeline } = require('../../utils/objectid-converter');
493
+ const convertedPipeline = convertAggregationPipeline(pipeline, 0, {
494
+ logger: context.logger,
495
+ excludeFields: context.autoConvertConfig?.excludeFields,
496
+ customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
497
+ maxDepth: context.autoConvertConfig?.maxDepth || 5
498
+ });
499
+
491
500
  // 构建 MongoDB watch 选项
492
501
  const watchOptions = {
493
502
  fullDocument: options.fullDocument || 'updateLookup',
@@ -501,13 +510,13 @@ function createWatchOps(context) {
501
510
  delete watchOptions.autoInvalidateCache;
502
511
 
503
512
  // 创建 MongoDB ChangeStream
504
- const changeStream = context.collection.watch(pipeline, watchOptions);
513
+ const changeStream = context.collection.watch(convertedPipeline, watchOptions);
505
514
 
506
515
  // 包装为 ChangeStreamWrapper
507
516
  const wrapper = new ChangeStreamWrapper(
508
517
  changeStream,
509
518
  context.collection,
510
- pipeline,
519
+ convertedPipeline,
511
520
  options,
512
521
  context
513
522
  );
@@ -0,0 +1,64 @@
1
+ /**
2
+ * 批量操作重试机制
3
+ * 供 insertBatch、deleteBatch、updateBatch 复用
4
+ */
5
+
6
+ /**
7
+ * 执行批次操作(带重试)
8
+ * @param {Function} fn - 要执行的批次操作函数
9
+ * @param {Object} retryContext - 重试上下文
10
+ * @param {string} retryContext.onError - 错误策略: 'stop'/'skip'/'collect'/'retry'
11
+ * @param {number} retryContext.retryAttempts - 最大重试次数
12
+ * @param {number} retryContext.retryDelay - 重试延迟(毫秒)
13
+ * @param {Function} retryContext.onRetry - 重试回调
14
+ * @param {number} retryContext.batchIndex - 当前批次索引
15
+ * @returns {Promise<Object>} { success, result, attempts }
16
+ */
17
+ async function executeBatchWithRetry(fn, retryContext) {
18
+ const {
19
+ onError = 'stop',
20
+ retryAttempts = 3,
21
+ retryDelay = 1000,
22
+ onRetry,
23
+ batchIndex = 0
24
+ } = retryContext;
25
+
26
+ let lastError = null;
27
+ let attempts = 0;
28
+ const maxAttempts = onError === 'retry' ? retryAttempts + 1 : 1;
29
+
30
+ while (attempts < maxAttempts) {
31
+ try {
32
+ const result = await fn();
33
+ return { success: true, result, attempts };
34
+ } catch (error) {
35
+ lastError = error;
36
+ attempts++;
37
+
38
+ // 还有重试机会
39
+ if (attempts < maxAttempts) {
40
+ // 触发重试回调
41
+ if (onRetry) {
42
+ onRetry({
43
+ batchIndex,
44
+ attempt: attempts,
45
+ maxAttempts: retryAttempts,
46
+ error,
47
+ nextRetryDelay: retryDelay
48
+ });
49
+ }
50
+
51
+ // 延迟后重试
52
+ if (retryDelay > 0) {
53
+ await new Promise(resolve => setTimeout(resolve, retryDelay));
54
+ }
55
+ }
56
+ }
57
+ }
58
+
59
+ // 所有重试都失败
60
+ throw lastError;
61
+ }
62
+
63
+ module.exports = { executeBatchWithRetry };
64
+
@@ -0,0 +1,322 @@
1
+ /**
2
+ * deleteBatch 操作实现
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 } = require('../../utils/objectid-converter');
10
+ const { executeBatchWithRetry } = require('./common/batch-retry');
11
+
12
+ /**
13
+ * 创建 deleteBatch 操作
14
+ * @param {Object} context - 模块上下文
15
+ * @returns {Object} 包含 deleteBatch 方法的对象
16
+ */
17
+ function createDeleteBatchOps(context) {
18
+ const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
19
+
20
+ const collectionName = collection.collectionName;
21
+ const nativeCollection = collection;
22
+
23
+ /**
24
+ * 分批删除大量匹配的文档
25
+ * @param {Object} filter - 筛选条件(必需)
26
+ * @param {Object} [options] - 操作选项
27
+ * @param {number} [options.batchSize=1000] - 每批删除的文档数量
28
+ * @param {boolean} [options.estimateProgress=true] - 是否预先 count 获取总数
29
+ * @param {Function} [options.onProgress] - 进度回调函数 (progress) => {}
30
+ * @param {string} [options.onError='stop'] - 错误处理策略: 'stop'/'skip'/'collect'/'retry'
31
+ * @param {number} [options.retryAttempts=3] - 失败批次最大重试次数
32
+ * @param {number} [options.retryDelay=1000] - 重试延迟时间(毫秒)
33
+ * @param {Function} [options.onRetry] - 重试回调函数 (retryInfo) => {}
34
+ * @param {Object} [options.writeConcern] - 写关注选项
35
+ * @param {string} [options.comment] - 操作注释(用于日志追踪)
36
+ * @returns {Promise<Object>} 删除结果
37
+ *
38
+ * @example
39
+ * const result = await collection('logs').deleteBatch(
40
+ * { createdAt: { $lt: new Date('2024-01-01') } },
41
+ * {
42
+ * batchSize: 1000,
43
+ * estimateProgress: true,
44
+ * onProgress: (p) => console.log(`进度: ${p.percentage}%`)
45
+ * }
46
+ * );
47
+ */
48
+ const deleteBatch = async function deleteBatch(filter, options = {}) {
49
+ const startTime = Date.now();
50
+
51
+ // 1. 参数验证
52
+ if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
53
+ throw createError(
54
+ ErrorCodes.INVALID_ARGUMENT,
55
+ 'filter 必须是对象类型',
56
+ [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
57
+ );
58
+ }
59
+
60
+ // 自动转换 ObjectId 字符串
61
+ const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
62
+ logger: context.logger,
63
+ excludeFields: context.autoConvertConfig?.excludeFields,
64
+ customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
65
+ maxDepth: context.autoConvertConfig?.maxDepth
66
+ });
67
+
68
+ // 解构选项
69
+ const {
70
+ batchSize = 1000,
71
+ estimateProgress = true,
72
+ onProgress,
73
+ onError = 'stop',
74
+ retryAttempts = 3,
75
+ retryDelay = 1000,
76
+ onRetry,
77
+ writeConcern,
78
+ comment
79
+ } = options;
80
+
81
+ // 2. 预先 count(可选)
82
+ const totalCount = estimateProgress
83
+ ? await nativeCollection.countDocuments(convertedFilter)
84
+ : null;
85
+
86
+ // 3. 初始化结果
87
+ const result = {
88
+ acknowledged: true,
89
+ totalCount,
90
+ deletedCount: 0,
91
+ batchCount: 0,
92
+ errors: [],
93
+ retries: []
94
+ };
95
+
96
+ // 4. 🔴 关键:直接调用 context 的 find 流式方法
97
+ const stream = await context.find(convertedFilter, {
98
+ stream: true,
99
+ batchSize,
100
+ limit: 0, // 🔴 重要:禁用默认的 limit,否则只会查询默认的 10 条
101
+ comment: comment ? `${comment}:deleteBatch` : 'deleteBatch'
102
+ });
103
+
104
+ let batch = [];
105
+
106
+ return new Promise((resolve, reject) => {
107
+ // 5. 监听数据事件
108
+ stream.on('data', async (doc) => {
109
+ batch.push(doc._id);
110
+
111
+ // 达到批次大小,执行删除
112
+ if (batch.length >= batchSize) {
113
+ stream.pause();
114
+
115
+ try {
116
+ // 🔴 带重试的批量删除
117
+ const batchResult = await executeBatchWithRetry(
118
+ () => nativeCollection.deleteMany(
119
+ { _id: { $in: batch } },
120
+ { writeConcern }
121
+ ),
122
+ { onError, retryAttempts, retryDelay, onRetry, batchIndex: result.batchCount }
123
+ );
124
+
125
+ result.deletedCount += batchResult.result.deletedCount;
126
+ result.batchCount++;
127
+
128
+ // 记录重试信息
129
+ if (batchResult.attempts > 0) {
130
+ result.retries.push({
131
+ batchIndex: result.batchCount - 1,
132
+ attempts: batchResult.attempts,
133
+ success: true
134
+ });
135
+ }
136
+
137
+ batch = [];
138
+
139
+ // 🔴 进度回调
140
+ if (onProgress) {
141
+ onProgress({
142
+ currentBatch: result.batchCount,
143
+ totalBatches: totalCount ? Math.ceil(totalCount / batchSize) : null,
144
+ deleted: result.deletedCount,
145
+ total: totalCount,
146
+ percentage: totalCount ? Math.round((result.deletedCount / totalCount) * 100) : null,
147
+ errors: result.errors.length,
148
+ retries: result.retries.length
149
+ });
150
+ }
151
+
152
+ stream.resume();
153
+
154
+ } catch (error) {
155
+ // 🔴 错误处理
156
+ result.errors.push({
157
+ batchIndex: result.batchCount,
158
+ batchSize: batch.length,
159
+ error: error,
160
+ message: error.message
161
+ });
162
+
163
+ if (onError === 'stop') {
164
+ stream.destroy();
165
+ reject(createError(
166
+ ErrorCodes.WRITE_ERROR,
167
+ `deleteBatch 操作失败: ${error.message}`,
168
+ null,
169
+ error
170
+ ));
171
+ return;
172
+ }
173
+
174
+ // skip 或 collect:清空批次,继续
175
+ batch = [];
176
+ result.batchCount++;
177
+ stream.resume();
178
+ }
179
+ }
180
+ });
181
+
182
+ // 6. 监听流结束事件
183
+ stream.on('end', async () => {
184
+ // 处理剩余的批次
185
+ if (batch.length > 0) {
186
+ try {
187
+ const batchResult = await executeBatchWithRetry(
188
+ () => nativeCollection.deleteMany(
189
+ { _id: { $in: batch } },
190
+ { writeConcern }
191
+ ),
192
+ { onError, retryAttempts, retryDelay, onRetry, batchIndex: result.batchCount }
193
+ );
194
+
195
+ result.deletedCount += batchResult.result.deletedCount;
196
+ result.batchCount++;
197
+
198
+ if (batchResult.attempts > 0) {
199
+ result.retries.push({
200
+ batchIndex: result.batchCount - 1,
201
+ attempts: batchResult.attempts,
202
+ success: true
203
+ });
204
+ }
205
+
206
+ // 最后一批的进度回调
207
+ if (onProgress) {
208
+ onProgress({
209
+ currentBatch: result.batchCount,
210
+ deleted: result.deletedCount,
211
+ total: totalCount,
212
+ percentage: totalCount ? 100 : null,
213
+ errors: result.errors.length,
214
+ retries: result.retries.length
215
+ });
216
+ }
217
+
218
+ } catch (error) {
219
+ result.errors.push({
220
+ batchIndex: result.batchCount,
221
+ batchSize: batch.length,
222
+ error: error,
223
+ message: error.message
224
+ });
225
+ }
226
+ }
227
+
228
+ // 7. 最终缓存失效
229
+ if (cache && result.deletedCount > 0) {
230
+ try {
231
+ const ns = {
232
+ iid: instanceId,
233
+ type: 'mongodb',
234
+ db: databaseName,
235
+ collection: collectionName
236
+ };
237
+ const pattern = CacheFactory.buildNamespacePattern(ns);
238
+
239
+ // 检查是否在事务中
240
+ if (isInTransaction(options)) {
241
+ const tx = getTransactionFromSession(options.session);
242
+ if (tx && typeof tx.recordInvalidation === 'function') {
243
+ await tx.recordInvalidation(pattern, {
244
+ operation: 'write',
245
+ query: filter || {},
246
+ collection: collectionName
247
+ });
248
+ logger.debug(`[deleteBatch] 事务中失效缓存: ${ns.db}.${ns.collection}`);
249
+ } else {
250
+ const deleted = await cache.delPattern(pattern);
251
+ if (deleted > 0) {
252
+ logger.debug(`[deleteBatch] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
253
+ }
254
+ }
255
+ } else {
256
+ const deleted = await cache.delPattern(pattern);
257
+ if (deleted > 0) {
258
+ logger.debug(`[deleteBatch] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
259
+ }
260
+ }
261
+ } catch (cacheErr) {
262
+ logger.warn(`[deleteBatch] 缓存失效失败: ${cacheErr.message}`);
263
+ }
264
+ }
265
+
266
+ // 8. 慢查询日志
267
+ const duration = Date.now() - startTime;
268
+ const slowQueryMs = defaults.slowQueryMs || 1000;
269
+
270
+ if (duration > slowQueryMs) {
271
+ logger.warn(`[deleteBatch] 慢操作警告`, {
272
+ ns: `${databaseName}.${collectionName}`,
273
+ duration,
274
+ threshold: slowQueryMs,
275
+ totalCount,
276
+ deletedCount: result.deletedCount,
277
+ batchCount: result.batchCount,
278
+ errorCount: result.errors.length,
279
+ retryCount: result.retries.length,
280
+ comment
281
+ });
282
+ } else {
283
+ logger.debug(`[deleteBatch] 操作完成`, {
284
+ ns: `${databaseName}.${collectionName}`,
285
+ duration,
286
+ deletedCount: result.deletedCount,
287
+ batchCount: result.batchCount
288
+ });
289
+ }
290
+
291
+ resolve(result);
292
+ });
293
+
294
+ // 9. 监听流错误事件
295
+ stream.on('error', (error) => {
296
+ logger.error(`[deleteBatch] 流式查询错误`, {
297
+ ns: `${databaseName}.${collectionName}`,
298
+ error: error.message,
299
+ code: error.code
300
+ });
301
+
302
+ result.errors.push({
303
+ batchIndex: result.batchCount,
304
+ error: error,
305
+ message: `流式查询错误: ${error.message}`
306
+ });
307
+
308
+ reject(createError(
309
+ ErrorCodes.WRITE_ERROR,
310
+ `deleteBatch 流式查询失败: ${error.message}`,
311
+ null,
312
+ error
313
+ ));
314
+ });
315
+ });
316
+ };
317
+
318
+ return { deleteBatch };
319
+ }
320
+
321
+ module.exports = { createDeleteBatchOps };
322
+
@@ -3,9 +3,10 @@
3
3
  * 删除所有匹配的文档
4
4
  */
5
5
 
6
- const { createError, ErrorCodes } = require("../../errors");
7
- const CacheFactory = require("../../cache");
8
- const { isInTransaction, getTransactionFromSession } = require("../common/transaction-aware");
6
+ const { createError, ErrorCodes } = require('../../errors');
7
+ const CacheFactory = require('../../cache');
8
+ const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
9
+ const { convertObjectIdStrings } = require('../../utils/objectid-converter');
9
10
 
10
11
  /**
11
12
  * 创建 deleteMany 操作
@@ -61,36 +62,44 @@ function createDeleteManyOps(context) {
61
62
  const startTime = Date.now();
62
63
 
63
64
  // 1. 参数验证
64
- if (!filter || typeof filter !== "object" || Array.isArray(filter)) {
65
+ if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
65
66
  throw createError(
66
67
  ErrorCodes.INVALID_ARGUMENT,
67
- "filter 必须是对象类型",
68
- [{ field: "filter", type: "object.required", message: "filter 是必需参数且必须是对象" }]
68
+ 'filter 必须是对象类型',
69
+ [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
69
70
  );
70
71
  }
71
72
 
73
+ // ✅ v1.3.0: 自动转换 ObjectId 字符串
74
+ const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
75
+ logger: context.logger,
76
+ excludeFields: context.autoConvertConfig?.excludeFields,
77
+ customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
78
+ maxDepth: context.autoConvertConfig?.maxDepth
79
+ });
80
+
72
81
  // 2. 警告:空 filter 会删除所有文档
73
- if (Object.keys(filter).length === 0) {
74
- logger.warn(`[deleteMany] 警告: 空 filter 将删除集合中的所有文档`, {
82
+ if (Object.keys(convertedFilter).length === 0) {
83
+ logger.warn('[deleteMany] 警告: 空 filter 将删除集合中的所有文档', {
75
84
  ns: `${databaseName}.${collectionName}`,
76
85
  comment: options.comment
77
86
  });
78
87
  }
79
88
 
80
89
  // 3. 构建操作上下文
81
- const operation = "deleteMany";
90
+ const operation = 'deleteMany';
82
91
  const ns = `${databaseName}.${collectionName}`;
83
92
 
84
93
  try {
85
94
  // 4. 执行删除操作
86
- const result = await nativeCollection.deleteMany(filter, options);
95
+ const result = await nativeCollection.deleteMany(convertedFilter, options);
87
96
 
88
97
  // 5. 自动失效缓存(如果有文档被删除)
89
98
  if (cache && result.deletedCount > 0) {
90
99
  try {
91
100
  const ns = {
92
101
  iid: instanceId,
93
- type: "mongodb",
102
+ type: 'mongodb',
94
103
  db: databaseName,
95
104
  collection: collectionName
96
105
  };
@@ -3,9 +3,10 @@
3
3
  * 删除单个匹配的文档
4
4
  */
5
5
 
6
- const { createError, ErrorCodes } = require("../../errors");
7
- const CacheFactory = require("../../cache");
8
- const { isInTransaction, getTransactionFromSession } = require("../common/transaction-aware");
6
+ const { createError, ErrorCodes } = require('../../errors');
7
+ const CacheFactory = require('../../cache');
8
+ const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
9
+ const { convertObjectIdStrings } = require('../../utils/objectid-converter');
9
10
 
10
11
  /**
11
12
  * 创建 deleteOne 操作
@@ -61,28 +62,36 @@ function createDeleteOneOps(context) {
61
62
  const startTime = Date.now();
62
63
 
63
64
  // 1. 参数验证
64
- if (!filter || typeof filter !== "object" || Array.isArray(filter)) {
65
+ if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
65
66
  throw createError(
66
67
  ErrorCodes.INVALID_ARGUMENT,
67
- "filter 必须是对象类型",
68
- [{ field: "filter", type: "object.required", message: "filter 是必需参数且必须是对象" }]
68
+ 'filter 必须是对象类型',
69
+ [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
69
70
  );
70
71
  }
71
72
 
73
+ // ✅ v1.3.0: 自动转换 ObjectId 字符串
74
+ const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
75
+ logger: context.logger,
76
+ excludeFields: context.autoConvertConfig?.excludeFields,
77
+ customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
78
+ maxDepth: context.autoConvertConfig?.maxDepth
79
+ });
80
+
72
81
  // 2. 构建操作上下文
73
- const operation = "deleteOne";
82
+ const operation = 'deleteOne';
74
83
  const ns = `${databaseName}.${collectionName}`;
75
84
 
76
85
  try {
77
86
  // 3. 执行删除操作
78
- const result = await nativeCollection.deleteOne(filter, options);
87
+ const result = await nativeCollection.deleteOne(convertedFilter, options);
79
88
 
80
89
  // 4. 自动失效缓存(如果有文档被删除)
81
90
  if (cache && result.deletedCount > 0) {
82
91
  try {
83
92
  const ns = {
84
93
  iid: instanceId,
85
- type: "mongodb",
94
+ type: 'mongodb',
86
95
  db: databaseName,
87
96
  collection: collectionName
88
97
  };