monsqlize 1.0.2 → 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.
@@ -38,6 +38,7 @@ const {
38
38
  createInsertBatchOps,
39
39
  createUpdateOneOps,
40
40
  createUpdateManyOps,
41
+ createUpdateBatchOps, // 🆕 批量更新
41
42
  createReplaceOneOps,
42
43
  createUpsertOneOps, // upsertOne 便利方法
43
44
  createIncrementOneOps, // 新增:incrementOne 便利方法
@@ -45,6 +46,7 @@ const {
45
46
  createFindOneAndReplaceOps,
46
47
  createDeleteOneOps,
47
48
  createDeleteManyOps,
49
+ createDeleteBatchOps, // 🆕 批量删除
48
50
  createFindOneAndDeleteOps
49
51
  } = require('./writes');
50
52
 
@@ -222,6 +224,7 @@ module.exports = class {
222
224
  const moduleContext = {
223
225
  collection,
224
226
  db,
227
+ collectionName: collection.collectionName, // 🔴 修复:添加 collectionName
225
228
  defaults: this.defaults,
226
229
  run,
227
230
  instanceId,
@@ -289,6 +292,20 @@ module.exports = class {
289
292
  });
290
293
  Object.assign(accessor, insertBatchOps);
291
294
 
295
+ // 🔑 关键:deleteBatch 依赖 find(流式查询),所以在 accessor 创建后添加
296
+ const deleteBatchOps = createDeleteBatchOps({
297
+ ...moduleContext,
298
+ find: accessor.find // 传入 find 方法(用于流式查询)
299
+ });
300
+ Object.assign(accessor, deleteBatchOps);
301
+
302
+ // 🔑 关键:updateBatch 依赖 find(流式查询),所以在 accessor 创建后添加
303
+ const updateBatchOps = createUpdateBatchOps({
304
+ ...moduleContext,
305
+ find: accessor.find // 传入 find 方法(用于流式查询)
306
+ });
307
+ Object.assign(accessor, updateBatchOps);
308
+
292
309
  // 🔑 关键:现在 accessor 已完整创建(包含 findPage),再创建依赖它的 bookmarkOps
293
310
  moduleContext.getCollectionMethods = () => accessor;
294
311
  const bookmarkOps = createBookmarkOps(moduleContext);
@@ -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
+
@@ -146,6 +146,12 @@ function createIncrementOneOps(context) {
146
146
  const returnDocument = actualOptions.returnDocument || 'after';
147
147
  const projection = actualOptions.projection;
148
148
 
149
+ // 🔧 Model 层 timestamps 支持:从 options.$set 读取额外的字段更新
150
+ if (actualOptions.$set && typeof actualOptions.$set === 'object') {
151
+ // 合并到 incUpdate
152
+ incUpdate.$set = actualOptions.$set;
153
+ }
154
+
149
155
  const updateOptions = {
150
156
  returnDocument,
151
157
  includeResultMetadata: true,
@@ -8,6 +8,7 @@ const { createInsertManyOps } = require('./insert-many');
8
8
  const { createInsertBatchOps } = require('./insert-batch');
9
9
  const { createUpdateOneOps } = require('./update-one');
10
10
  const { createUpdateManyOps } = require('./update-many');
11
+ const { createUpdateBatchOps } = require('./update-batch'); // 🆕 批量更新
11
12
  const { createReplaceOneOps } = require('./replace-one');
12
13
  const { createUpsertOneOps } = require('./upsert-one'); // upsertOne 便利方法
13
14
  const { createIncrementOneOps } = require('./increment-one'); // 新增:incrementOne 便利方法
@@ -15,6 +16,7 @@ const { createFindOneAndUpdateOps } = require('./find-one-and-update');
15
16
  const { createFindOneAndReplaceOps } = require('./find-one-and-replace');
16
17
  const { createDeleteOneOps } = require('./delete-one');
17
18
  const { createDeleteManyOps } = require('./delete-many');
19
+ const { createDeleteBatchOps } = require('./delete-batch'); // 🆕 批量删除
18
20
  const { createFindOneAndDeleteOps } = require('./find-one-and-delete');
19
21
 
20
22
  module.exports = {
@@ -26,6 +28,7 @@ module.exports = {
26
28
  // Update 操作
27
29
  createUpdateOneOps,
28
30
  createUpdateManyOps,
31
+ createUpdateBatchOps, // 🆕 批量更新
29
32
  createReplaceOneOps,
30
33
  createUpsertOneOps, // upsertOne 便利方法
31
34
  createIncrementOneOps, // 新增:incrementOne 便利方法
@@ -37,5 +40,6 @@ module.exports = {
37
40
  // Delete 操作
38
41
  createDeleteOneOps,
39
42
  createDeleteManyOps,
43
+ createDeleteBatchOps, // 🆕 批量删除
40
44
  createFindOneAndDeleteOps,
41
45
  };