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.
- package/CHANGELOG.md +56 -60
- package/LICENSE +201 -21
- package/README.md +537 -1828
- package/changelogs/README.md +160 -0
- package/changelogs/v2.0.0.md +222 -0
- package/dist/cjs/index.cjs +10600 -0
- package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
- package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
- package/dist/cjs/transaction/Transaction.cjs +158 -0
- package/dist/cjs/transaction/TransactionManager.cjs +298 -0
- package/dist/esm/index.mjs +10650 -0
- package/dist/types/base.d.ts +81 -0
- package/dist/types/collection.d.ts +1031 -0
- package/dist/types/expression.d.ts +115 -0
- package/dist/types/index.d.ts +23 -0
- package/dist/types/lock.d.ts +74 -0
- package/dist/types/model.d.ts +526 -0
- package/dist/types/mongodb.d.ts +49 -0
- package/dist/types/monsqlize.d.ts +491 -0
- package/dist/types/pool.d.ts +84 -0
- package/dist/types/runtime.d.ts +362 -0
- package/dist/types/saga.d.ts +143 -0
- package/dist/types/slow-query-log.d.ts +126 -0
- package/dist/types/sync.d.ts +103 -0
- package/dist/types/transaction.d.ts +132 -0
- package/package.json +67 -69
- package/index.d.ts +0 -206
- package/index.mjs +0 -52
- package/lib/cache-invalidation.js +0 -279
- package/lib/cache.js +0 -530
- package/lib/common/cursor.js +0 -59
- package/lib/common/docs-urls.js +0 -73
- package/lib/common/index-options.js +0 -223
- package/lib/common/log.js +0 -61
- package/lib/common/namespace.js +0 -22
- package/lib/common/normalize.js +0 -34
- package/lib/common/page-result.js +0 -43
- package/lib/common/runner.js +0 -57
- package/lib/common/server-features.js +0 -232
- package/lib/common/shape-builders.js +0 -27
- package/lib/common/validation.js +0 -113
- package/lib/connect.js +0 -99
- package/lib/constants.js +0 -55
- package/lib/count-queue.js +0 -188
- package/lib/distributed-cache-invalidator.js +0 -260
- package/lib/errors.js +0 -168
- package/lib/expression/cache/ExpressionCache.js +0 -114
- package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
- package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
- package/lib/expression/detector.js +0 -84
- package/lib/expression/factory.js +0 -29
- package/lib/expression/index.js +0 -19
- package/lib/function-cache.js +0 -533
- package/lib/index.js +0 -1251
- package/lib/infrastructure/ConnectionPoolManager.js +0 -464
- package/lib/infrastructure/HealthChecker.js +0 -281
- package/lib/infrastructure/PoolConfig.js +0 -199
- package/lib/infrastructure/PoolSelector.js +0 -225
- package/lib/infrastructure/PoolStats.js +0 -244
- package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
- package/lib/infrastructure/ssh-tunnel.js +0 -41
- package/lib/infrastructure/uri-parser.js +0 -36
- package/lib/lock/Lock.js +0 -67
- package/lib/lock/errors.js +0 -28
- package/lib/lock/index.js +0 -13
- package/lib/logger.js +0 -225
- package/lib/model/examples/test.js +0 -311
- package/lib/model/features/defaults.js +0 -161
- package/lib/model/features/populate.js +0 -568
- package/lib/model/features/relations.js +0 -120
- package/lib/model/features/soft-delete.js +0 -349
- package/lib/model/features/version.js +0 -157
- package/lib/model/features/virtuals.js +0 -219
- package/lib/model/index.js +0 -1265
- package/lib/mongodb/common/accessor-helpers.js +0 -59
- package/lib/mongodb/common/agg-pipeline.js +0 -36
- package/lib/mongodb/common/aggregation-validator.js +0 -127
- package/lib/mongodb/common/iid.js +0 -28
- package/lib/mongodb/common/lexicographic-expr.js +0 -53
- package/lib/mongodb/common/shape.js +0 -32
- package/lib/mongodb/common/sort.js +0 -39
- package/lib/mongodb/common/transaction-aware.js +0 -25
- package/lib/mongodb/connect.js +0 -234
- package/lib/mongodb/index.js +0 -639
- package/lib/mongodb/management/admin-ops.js +0 -200
- package/lib/mongodb/management/bookmark-ops.js +0 -167
- package/lib/mongodb/management/cache-ops.js +0 -50
- package/lib/mongodb/management/collection-ops.js +0 -387
- package/lib/mongodb/management/database-ops.js +0 -202
- package/lib/mongodb/management/index-ops.js +0 -475
- package/lib/mongodb/management/index.js +0 -17
- package/lib/mongodb/management/namespace.js +0 -31
- package/lib/mongodb/management/validation-ops.js +0 -268
- package/lib/mongodb/queries/aggregate.js +0 -172
- package/lib/mongodb/queries/chain.js +0 -631
- package/lib/mongodb/queries/count.js +0 -99
- package/lib/mongodb/queries/distinct.js +0 -78
- package/lib/mongodb/queries/find-and-count.js +0 -193
- package/lib/mongodb/queries/find-by-ids.js +0 -236
- package/lib/mongodb/queries/find-one-by-id.js +0 -171
- package/lib/mongodb/queries/find-one.js +0 -71
- package/lib/mongodb/queries/find-page.js +0 -618
- package/lib/mongodb/queries/find.js +0 -171
- package/lib/mongodb/queries/index.js +0 -51
- package/lib/mongodb/queries/watch.js +0 -538
- package/lib/mongodb/writes/common/batch-retry.js +0 -65
- package/lib/mongodb/writes/delete-batch.js +0 -323
- package/lib/mongodb/writes/delete-many.js +0 -181
- package/lib/mongodb/writes/delete-one.js +0 -173
- package/lib/mongodb/writes/find-one-and-delete.js +0 -203
- package/lib/mongodb/writes/find-one-and-replace.js +0 -239
- package/lib/mongodb/writes/find-one-and-update.js +0 -240
- package/lib/mongodb/writes/increment-one.js +0 -259
- package/lib/mongodb/writes/index.js +0 -46
- package/lib/mongodb/writes/insert-batch.js +0 -508
- package/lib/mongodb/writes/insert-many.js +0 -223
- package/lib/mongodb/writes/insert-one.js +0 -169
- package/lib/mongodb/writes/replace-one.js +0 -226
- package/lib/mongodb/writes/result-handler.js +0 -237
- package/lib/mongodb/writes/update-batch.js +0 -416
- package/lib/mongodb/writes/update-many.js +0 -275
- package/lib/mongodb/writes/update-one.js +0 -273
- package/lib/mongodb/writes/upsert-one.js +0 -203
- package/lib/multi-level-cache.js +0 -244
- package/lib/operators.js +0 -330
- package/lib/redis-cache-adapter.js +0 -267
- package/lib/saga/SagaContext.js +0 -67
- package/lib/saga/SagaDefinition.js +0 -32
- package/lib/saga/SagaExecutor.js +0 -201
- package/lib/saga/SagaOrchestrator.js +0 -186
- package/lib/saga/index.js +0 -11
- package/lib/slow-query-log/base-storage.js +0 -70
- package/lib/slow-query-log/batch-queue.js +0 -97
- package/lib/slow-query-log/config-manager.js +0 -196
- package/lib/slow-query-log/index.js +0 -238
- package/lib/slow-query-log/mongodb-storage.js +0 -324
- package/lib/slow-query-log/query-hash.js +0 -39
- package/lib/sync/ChangeStreamSyncManager.js +0 -405
- package/lib/sync/ResumeTokenStore.js +0 -192
- package/lib/sync/SyncConfig.js +0 -127
- package/lib/sync/SyncTarget.js +0 -240
- package/lib/sync/index.js +0 -20
- package/lib/transaction/CacheLockManager.js +0 -162
- package/lib/transaction/DistributedCacheLockManager.js +0 -475
- package/lib/transaction/Transaction.js +0 -315
- package/lib/transaction/TransactionManager.js +0 -267
- package/lib/transaction/index.js +0 -11
- package/lib/utils/objectid-converter.js +0 -632
- package/types/README.md +0 -122
- package/types/base.ts +0 -94
- package/types/batch.ts +0 -187
- package/types/cache.ts +0 -71
- package/types/chain.ts +0 -254
- package/types/collection.ts +0 -357
- package/types/expression.ts +0 -109
- package/types/function-cache.d.ts +0 -135
- package/types/lock.ts +0 -95
- package/types/model/definition.ts +0 -152
- package/types/model/index.ts +0 -10
- package/types/model/instance.ts +0 -121
- package/types/model/relations.ts +0 -121
- package/types/model/virtuals.ts +0 -32
- package/types/monsqlize.ts +0 -245
- package/types/options.ts +0 -192
- package/types/pagination.ts +0 -154
- package/types/pool.ts +0 -125
- package/types/query.ts +0 -71
- package/types/saga.ts +0 -125
- package/types/stream.ts +0 -64
- package/types/sync.ts +0 -79
- package/types/transaction.ts +0 -79
- package/types/write.ts +0 -77
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* findOneAnd* 操作返回值处理工具
|
|
3
|
-
* 统一处理 MongoDB 驱动返回值的各种边界情况
|
|
4
|
-
*
|
|
5
|
-
* **重要说明 - MongoDB 驱动版本兼容性**
|
|
6
|
-
*
|
|
7
|
-
* 本模块专门处理 MongoDB Node.js 驱动在不同版本间的 API 差异:
|
|
8
|
-
*
|
|
9
|
-
* - **MongoDB 驱动 6.x** (当前支持):
|
|
10
|
-
* - `findOneAnd*` 方法默认直接返回文档对象
|
|
11
|
-
* - 需要显式传递 `includeResultMetadata: true` 才返回完整元数据
|
|
12
|
-
*
|
|
13
|
-
* - **MongoDB 驱动 5.x 及更早版本**:
|
|
14
|
-
* - `findOneAnd*` 方法默认返回 `{ value, ok, lastErrorObject }` 格式
|
|
15
|
-
*
|
|
16
|
-
* **兼容性保证**:
|
|
17
|
-
* - 本模块会自动检测和处理驱动返回值格式的差异
|
|
18
|
-
* - monSQLize 的公共 API 行为保持一致,用户无需关心驱动版本
|
|
19
|
-
* - 如果未来驱动版本再次变更,仅需修改本模块即可
|
|
20
|
-
*
|
|
21
|
-
* **维护建议**:
|
|
22
|
-
* - 升级 MongoDB 驱动前,务必运行完整测试套件
|
|
23
|
-
* - 关注 MongoDB 驱动的 CHANGELOG,特别是 `findOneAnd*` 方法的变更
|
|
24
|
-
* - 如有疑问,参考技术分析报告:`analysis-reports/2025-11-17-mongodb-driver-6x-compatibility-FINAL.md`
|
|
25
|
-
*
|
|
26
|
-
* @module result-handler
|
|
27
|
-
* @since 2025-11-17
|
|
28
|
-
*/
|
|
29
|
-
|
|
30
|
-
// MongoDB 驱动版本检测(用于诊断和警告)
|
|
31
|
-
let _driverVersionChecked = false;
|
|
32
|
-
let _detectedDriverMajorVersion = null;
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* 检测 MongoDB 驱动版本(仅在第一次调用时执行)
|
|
36
|
-
* @private
|
|
37
|
-
* @returns {number|null} 驱动主版本号,如果无法检测则返回 null
|
|
38
|
-
*/
|
|
39
|
-
function detectDriverVersion() {
|
|
40
|
-
if (_driverVersionChecked) {
|
|
41
|
-
return _detectedDriverMajorVersion;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
_driverVersionChecked = true;
|
|
45
|
-
|
|
46
|
-
try {
|
|
47
|
-
const mongodb = require('mongodb');
|
|
48
|
-
const versionString = mongodb.version || require('mongodb/package.json').version;
|
|
49
|
-
const match = versionString.match(/^(\d+)\./);
|
|
50
|
-
if (match) {
|
|
51
|
-
_detectedDriverMajorVersion = parseInt(match[1], 10);
|
|
52
|
-
return _detectedDriverMajorVersion;
|
|
53
|
-
}
|
|
54
|
-
} catch (error) {
|
|
55
|
-
// 无法检测版本,静默失败
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
return null;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* 记录驱动版本警告(仅在检测到不支持的版本时)
|
|
63
|
-
* @private
|
|
64
|
-
* @param {Object} logger - 日志实例
|
|
65
|
-
*/
|
|
66
|
-
function warnUnsupportedDriverVersion(logger) {
|
|
67
|
-
const version = detectDriverVersion();
|
|
68
|
-
|
|
69
|
-
if (version === null) {
|
|
70
|
-
// 无法检测版本,不输出警告(避免误报)
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
if (version < 6) {
|
|
75
|
-
// 驱动版本小于 6.x,可能不兼容
|
|
76
|
-
if (logger && logger.warn) {
|
|
77
|
-
logger.warn('[result-handler] ⚠️ 检测到 MongoDB 驱动版本过旧', {
|
|
78
|
-
detectedVersion: version,
|
|
79
|
-
supportedVersion: '6.x',
|
|
80
|
-
message: 'monSQLize 专为 MongoDB 驱动 6.x 设计,旧版本可能存在兼容性问题',
|
|
81
|
-
recommendation: '建议升级到 MongoDB Node.js 驱动 ^6.0.0'
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
} else if (version > 6) {
|
|
85
|
-
// 驱动版本大于 6.x,未经测试
|
|
86
|
-
if (logger && logger.warn) {
|
|
87
|
-
logger.warn('[result-handler] ⚠️ 检测到 MongoDB 驱动版本未经测试', {
|
|
88
|
-
detectedVersion: version,
|
|
89
|
-
testedVersion: '6.x',
|
|
90
|
-
message: 'monSQLize 已针对 MongoDB 驱动 6.x 测试,新版本可能存在未知问题',
|
|
91
|
-
recommendation: '如遇问题,请查看技术分析报告或回退到驱动 6.x'
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
// 版本 === 6,无需警告
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* 处理 findOneAnd* 操作的返回值
|
|
100
|
-
* 统一处理各种边界情况,确保返回值格式的一致性
|
|
101
|
-
*
|
|
102
|
-
* @param {Object|null} result - MongoDB 驱动返回的结果
|
|
103
|
-
* @param {Object} options - 操作选项
|
|
104
|
-
* @param {boolean} [options.includeResultMetadata=false] - 是否返回完整元数据
|
|
105
|
-
* @param {Object} [logger] - 日志实例(可选,用于诊断)
|
|
106
|
-
* @returns {Object|null} 处理后的结果
|
|
107
|
-
*
|
|
108
|
-
* @example
|
|
109
|
-
* // 正常情况(找到文档)
|
|
110
|
-
* const result = { value: { name: "Alice" }, ok: 1, lastErrorObject: { n: 1, updatedExisting: true } };
|
|
111
|
-
* handleFindOneAndResult(result, {}); // 返回: { name: "Alice" }
|
|
112
|
-
*
|
|
113
|
-
* @example
|
|
114
|
-
* // 未找到文档
|
|
115
|
-
* const result = { value: null, ok: 1, lastErrorObject: { n: 0 } };
|
|
116
|
-
* handleFindOneAndResult(result, {}); // 返回: null
|
|
117
|
-
*
|
|
118
|
-
* @example
|
|
119
|
-
* // result 为 null(驱动异常情况)
|
|
120
|
-
* handleFindOneAndResult(null, {}); // 返回: null
|
|
121
|
-
*
|
|
122
|
-
* @example
|
|
123
|
-
* // 返回完整元数据
|
|
124
|
-
* handleFindOneAndResult(null, { includeResultMetadata: true });
|
|
125
|
-
* // 返回: { value: null, ok: 1, lastErrorObject: { n: 0 } }
|
|
126
|
-
*/
|
|
127
|
-
function handleFindOneAndResult(result, options = {}, logger = null) {
|
|
128
|
-
// 首次调用时检测驱动版本并输出警告(如果需要)
|
|
129
|
-
if (!_driverVersionChecked && logger) {
|
|
130
|
-
warnUnsupportedDriverVersion(logger);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// 情况 1:result 为 null 或 undefined(驱动在某些边界情况下可能返回 null)
|
|
134
|
-
if (!result || result === null) {
|
|
135
|
-
if (logger && logger.debug) {
|
|
136
|
-
logger.debug('[result-handler] Result is null/undefined, returning empty result', {
|
|
137
|
-
includeMetadata: options.includeResultMetadata
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
if (options.includeResultMetadata) {
|
|
142
|
-
// 返回标准的空结果元数据
|
|
143
|
-
return {
|
|
144
|
-
value: null,
|
|
145
|
-
ok: 1,
|
|
146
|
-
lastErrorObject: { n: 0 }
|
|
147
|
-
};
|
|
148
|
-
} else {
|
|
149
|
-
// 仅返回 null
|
|
150
|
-
return null;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
// 情况 2:result 是对象但缺少 lastErrorObject(驱动版本差异或异常情况)
|
|
155
|
-
if (typeof result === 'object' && !result.lastErrorObject) {
|
|
156
|
-
if (logger && logger.warn) {
|
|
157
|
-
logger.warn('[result-handler] ⚠️ Result missing lastErrorObject, possible driver version issue', {
|
|
158
|
-
hasValue: result.value !== undefined,
|
|
159
|
-
hasOk: result.ok !== undefined,
|
|
160
|
-
resultKeys: Object.keys(result),
|
|
161
|
-
driverVersion: detectDriverVersion(),
|
|
162
|
-
recommendation: '这可能表明 MongoDB 驱动返回了非预期的格式,请检查驱动版本'
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
const hasValue = result.value !== null && result.value !== undefined;
|
|
167
|
-
// 补充缺失的 lastErrorObject
|
|
168
|
-
result.lastErrorObject = {
|
|
169
|
-
n: hasValue ? 1 : 0
|
|
170
|
-
};
|
|
171
|
-
// 如果有值,假设是更新/替换操作成功
|
|
172
|
-
if (hasValue) {
|
|
173
|
-
result.lastErrorObject.updatedExisting = true;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// 情况 3:result 是对象且包含 lastErrorObject(正常情况)
|
|
178
|
-
if (options.includeResultMetadata) {
|
|
179
|
-
// 返回完整元数据:{ value, ok, lastErrorObject }
|
|
180
|
-
return result;
|
|
181
|
-
} else {
|
|
182
|
-
// 仅返回文档(可能为 null)
|
|
183
|
-
return result.value !== undefined ? result.value : null;
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* 判断操作是否修改了文档(用于缓存失效逻辑)
|
|
189
|
-
* 安全地检查 MongoDB 操作是否成功修改了文档
|
|
190
|
-
*
|
|
191
|
-
* @param {Object|null} result - MongoDB 驱动返回的结果
|
|
192
|
-
* @returns {boolean} 是否修改/删除了文档
|
|
193
|
-
*
|
|
194
|
-
* @example
|
|
195
|
-
* // 更新成功
|
|
196
|
-
* const result = { value: {...}, lastErrorObject: { updatedExisting: true } };
|
|
197
|
-
* wasDocumentModified(result); // 返回: true
|
|
198
|
-
*
|
|
199
|
-
* @example
|
|
200
|
-
* // Upsert 插入
|
|
201
|
-
* const result = { value: {...}, lastErrorObject: { upserted: ObjectId(...) } };
|
|
202
|
-
* wasDocumentModified(result); // 返回: true
|
|
203
|
-
*
|
|
204
|
-
* @example
|
|
205
|
-
* // 未找到文档
|
|
206
|
-
* const result = { value: null, lastErrorObject: { n: 0 } };
|
|
207
|
-
* wasDocumentModified(result); // 返回: false
|
|
208
|
-
*
|
|
209
|
-
* @example
|
|
210
|
-
* // 删除成功(有返回值)
|
|
211
|
-
* const result = { value: {...}, lastErrorObject: { n: 1 } };
|
|
212
|
-
* wasDocumentModified(result); // 返回: true
|
|
213
|
-
*/
|
|
214
|
-
function wasDocumentModified(result) {
|
|
215
|
-
// 安全检查:result 或 lastErrorObject 不存在
|
|
216
|
-
if (!result || !result.lastErrorObject) {
|
|
217
|
-
return false;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// 检查修改标志
|
|
221
|
-
return !!(
|
|
222
|
-
// 更新/替换操作:文档已存在并被修改
|
|
223
|
-
result.lastErrorObject.updatedExisting ||
|
|
224
|
-
// Upsert 操作:插入了新文档
|
|
225
|
-
result.lastErrorObject.upserted ||
|
|
226
|
-
// 删除操作:有文档被删除(通过 n > 0 或 value 不为 null 判断)
|
|
227
|
-
(result.lastErrorObject.n > 0) ||
|
|
228
|
-
(result.value !== null && result.value !== undefined)
|
|
229
|
-
);
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
module.exports = {
|
|
233
|
-
handleFindOneAndResult,
|
|
234
|
-
wasDocumentModified
|
|
235
|
-
};
|
|
236
|
-
|
|
237
|
-
|
|
@@ -1,416 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* updateBatch 操作实现
|
|
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 { executeBatchWithRetry } = require('./common/batch-retry');
|
|
11
|
-
const { validateAggregationPipeline, isAggregationPipeline } = require('../common/aggregation-validator');
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* 创建 updateBatch 操作
|
|
15
|
-
* @param {Object} context - 模块上下文
|
|
16
|
-
* @returns {Object} 包含 updateBatch 方法的对象
|
|
17
|
-
*/
|
|
18
|
-
function createUpdateBatchOps(context) {
|
|
19
|
-
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
20
|
-
|
|
21
|
-
const collectionName = collection.collectionName;
|
|
22
|
-
const nativeCollection = collection;
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* 分批更新大量匹配的文档
|
|
26
|
-
* @param {Object} filter - 筛选条件(必需)
|
|
27
|
-
* @param {Object} update - 更新操作(必需,使用更新操作符如 $set)
|
|
28
|
-
* @param {Object} [options] - 操作选项
|
|
29
|
-
* @param {number} [options.batchSize=1000] - 每批更新的文档数量
|
|
30
|
-
* @param {boolean} [options.estimateProgress=true] - 是否预先 count 获取总数
|
|
31
|
-
* @param {Function} [options.onProgress] - 进度回调函数 (progress) => {}
|
|
32
|
-
* @param {string} [options.onError='stop'] - 错误处理策略: 'stop'/'skip'/'collect'/'retry'
|
|
33
|
-
* @param {number} [options.retryAttempts=3] - 失败批次最大重试次数
|
|
34
|
-
* @param {number} [options.retryDelay=1000] - 重试延迟时间(毫秒)
|
|
35
|
-
* @param {Function} [options.onRetry] - 重试回调函数 (retryInfo) => {}
|
|
36
|
-
* @param {Object} [options.writeConcern] - 写关注选项
|
|
37
|
-
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
38
|
-
* @returns {Promise<Object>} 更新结果
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* const result = await collection('orders').updateBatch(
|
|
42
|
-
* { status: 'pending', createdAt: { $lt: expiredDate } },
|
|
43
|
-
* { $set: { status: 'expired' } },
|
|
44
|
-
* {
|
|
45
|
-
* batchSize: 500,
|
|
46
|
-
* estimateProgress: true,
|
|
47
|
-
* onProgress: (p) => console.log(`进度: ${p.percentage}%`)
|
|
48
|
-
* }
|
|
49
|
-
* );
|
|
50
|
-
*/
|
|
51
|
-
const updateBatch = async function updateBatch(filter, update, options = {}) {
|
|
52
|
-
const startTime = Date.now();
|
|
53
|
-
|
|
54
|
-
// 1. 参数验证
|
|
55
|
-
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
|
|
56
|
-
throw createError(
|
|
57
|
-
ErrorCodes.INVALID_ARGUMENT,
|
|
58
|
-
'filter 必须是对象类型',
|
|
59
|
-
[{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
|
|
60
|
-
);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
if (!update || (typeof update !== 'object' && !Array.isArray(update))) {
|
|
64
|
-
throw createError(
|
|
65
|
-
ErrorCodes.INVALID_ARGUMENT,
|
|
66
|
-
'update 必须是对象(更新操作符)或数组(聚合管道)',
|
|
67
|
-
[{ field: 'update', type: 'object|array.required', message: 'update 必须是更新操作符对象或聚合管道数组' }]
|
|
68
|
-
);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// 检测聚合管道模式
|
|
72
|
-
const isAggregation = isAggregationPipeline(update);
|
|
73
|
-
|
|
74
|
-
if (isAggregation) {
|
|
75
|
-
// 验证聚合管道格式
|
|
76
|
-
validateAggregationPipeline(update);
|
|
77
|
-
|
|
78
|
-
if (logger && logger.debug) {
|
|
79
|
-
logger.debug(`[updateBatch] 使用聚合管道模式`, {
|
|
80
|
-
collection: collectionName,
|
|
81
|
-
stagesCount: update.length,
|
|
82
|
-
operators: update.map(stage => Object.keys(stage)[0])
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
} else {
|
|
86
|
-
// 验证 update 包含更新操作符
|
|
87
|
-
const updateKeys = Object.keys(update);
|
|
88
|
-
|
|
89
|
-
// 检查空对象
|
|
90
|
-
if (updateKeys.length === 0) {
|
|
91
|
-
throw createError(
|
|
92
|
-
ErrorCodes.INVALID_ARGUMENT,
|
|
93
|
-
'update 不能为空对象',
|
|
94
|
-
[{ field: 'update', type: 'object.empty', message: 'update 必须包含至少一个更新操作符' }]
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// 检查是否包含操作符
|
|
99
|
-
if (!updateKeys.some(key => key.startsWith('$'))) {
|
|
100
|
-
throw createError(
|
|
101
|
-
ErrorCodes.INVALID_ARGUMENT,
|
|
102
|
-
'update 必须使用更新操作符(如 $set, $inc 等)',
|
|
103
|
-
[{ field: 'update', type: 'object.invalid', message: '请使用 $set, $inc, $push 等更新操作符' }]
|
|
104
|
-
);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// 自动转换 ObjectId 字符串
|
|
109
|
-
const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
|
|
110
|
-
logger: context.logger,
|
|
111
|
-
excludeFields: context.autoConvertConfig?.excludeFields,
|
|
112
|
-
customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
|
|
113
|
-
maxDepth: context.autoConvertConfig?.maxDepth
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
// ✅ v1.0.8: 聚合管道不转换 ObjectId(保持原样)
|
|
117
|
-
const convertedUpdate = isAggregation
|
|
118
|
-
? update // 聚合管道保持原样
|
|
119
|
-
: convertUpdateDocument(update, {
|
|
120
|
-
logger: context.logger,
|
|
121
|
-
excludeFields: context.autoConvertConfig?.excludeFields,
|
|
122
|
-
customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
|
|
123
|
-
maxDepth: context.autoConvertConfig?.maxDepth
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
// 解构选项
|
|
127
|
-
const {
|
|
128
|
-
batchSize = 1000,
|
|
129
|
-
estimateProgress = true,
|
|
130
|
-
onProgress,
|
|
131
|
-
onError = 'stop',
|
|
132
|
-
retryAttempts = 3,
|
|
133
|
-
retryDelay = 1000,
|
|
134
|
-
onRetry,
|
|
135
|
-
writeConcern,
|
|
136
|
-
comment
|
|
137
|
-
} = options;
|
|
138
|
-
|
|
139
|
-
// 2. 预先 count(可选)
|
|
140
|
-
const totalCount = estimateProgress
|
|
141
|
-
? await nativeCollection.countDocuments(convertedFilter)
|
|
142
|
-
: null;
|
|
143
|
-
|
|
144
|
-
// 3. 初始化结果
|
|
145
|
-
const result = {
|
|
146
|
-
acknowledged: true,
|
|
147
|
-
totalCount,
|
|
148
|
-
matchedCount: 0,
|
|
149
|
-
modifiedCount: 0,
|
|
150
|
-
batchCount: 0,
|
|
151
|
-
errors: [],
|
|
152
|
-
retries: []
|
|
153
|
-
};
|
|
154
|
-
|
|
155
|
-
// 4. 🔴 关键:直接调用 context 的 find 流式方法
|
|
156
|
-
const stream = await context.find(convertedFilter, {
|
|
157
|
-
stream: true,
|
|
158
|
-
batchSize,
|
|
159
|
-
limit: 0, // 🔴 重要:禁用默认的 limit,否则只会查询默认的 10 条
|
|
160
|
-
comment: comment ? `${comment}:updateBatch` : 'updateBatch'
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
let batch = [];
|
|
164
|
-
|
|
165
|
-
return new Promise((resolve, reject) => {
|
|
166
|
-
// 5. 监听数据事件
|
|
167
|
-
stream.on('data', async (doc) => {
|
|
168
|
-
batch.push(doc._id);
|
|
169
|
-
|
|
170
|
-
// 达到批次大小,执行更新
|
|
171
|
-
if (batch.length >= batchSize) {
|
|
172
|
-
stream.pause();
|
|
173
|
-
|
|
174
|
-
try {
|
|
175
|
-
// 🔴 带重试的批量更新
|
|
176
|
-
const batchResult = await executeBatchWithRetry(
|
|
177
|
-
() => nativeCollection.updateMany(
|
|
178
|
-
{ _id: { $in: batch } },
|
|
179
|
-
convertedUpdate,
|
|
180
|
-
{ writeConcern }
|
|
181
|
-
),
|
|
182
|
-
{ onError, retryAttempts, retryDelay, onRetry, batchIndex: result.batchCount }
|
|
183
|
-
);
|
|
184
|
-
|
|
185
|
-
result.matchedCount += batchResult.result.matchedCount;
|
|
186
|
-
result.modifiedCount += batchResult.result.modifiedCount;
|
|
187
|
-
result.batchCount++;
|
|
188
|
-
|
|
189
|
-
// 记录重试信息
|
|
190
|
-
if (batchResult.attempts > 0) {
|
|
191
|
-
result.retries.push({
|
|
192
|
-
batchIndex: result.batchCount - 1,
|
|
193
|
-
attempts: batchResult.attempts,
|
|
194
|
-
success: true
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
batch = [];
|
|
199
|
-
|
|
200
|
-
// 🔴 进度回调
|
|
201
|
-
if (onProgress) {
|
|
202
|
-
onProgress({
|
|
203
|
-
currentBatch: result.batchCount,
|
|
204
|
-
totalBatches: totalCount ? Math.ceil(totalCount / batchSize) : null,
|
|
205
|
-
matched: result.matchedCount,
|
|
206
|
-
modified: result.modifiedCount,
|
|
207
|
-
total: totalCount,
|
|
208
|
-
percentage: totalCount ? Math.round((result.matchedCount / totalCount) * 100) : null,
|
|
209
|
-
errors: result.errors.length,
|
|
210
|
-
retries: result.retries.length
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
stream.resume();
|
|
215
|
-
|
|
216
|
-
} catch (error) {
|
|
217
|
-
// 🔴 错误处理
|
|
218
|
-
result.errors.push({
|
|
219
|
-
batchIndex: result.batchCount,
|
|
220
|
-
batchSize: batch.length,
|
|
221
|
-
error: error,
|
|
222
|
-
message: error.message
|
|
223
|
-
});
|
|
224
|
-
|
|
225
|
-
if (onError === 'stop') {
|
|
226
|
-
stream.destroy();
|
|
227
|
-
reject(createError(
|
|
228
|
-
ErrorCodes.WRITE_ERROR,
|
|
229
|
-
`updateBatch 操作失败: ${error.message}`,
|
|
230
|
-
null,
|
|
231
|
-
error
|
|
232
|
-
));
|
|
233
|
-
return;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// skip 或 collect:清空批次,继续
|
|
237
|
-
batch = [];
|
|
238
|
-
result.batchCount++;
|
|
239
|
-
stream.resume();
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
});
|
|
243
|
-
|
|
244
|
-
// 6. 监听流结束事件
|
|
245
|
-
stream.on('end', async () => {
|
|
246
|
-
// 处理剩余的批次
|
|
247
|
-
if (batch.length > 0) {
|
|
248
|
-
try {
|
|
249
|
-
const batchResult = await executeBatchWithRetry(
|
|
250
|
-
() => nativeCollection.updateMany(
|
|
251
|
-
{ _id: { $in: batch } },
|
|
252
|
-
convertedUpdate,
|
|
253
|
-
{ writeConcern }
|
|
254
|
-
),
|
|
255
|
-
{ onError, retryAttempts, retryDelay, onRetry, batchIndex: result.batchCount }
|
|
256
|
-
);
|
|
257
|
-
|
|
258
|
-
result.matchedCount += batchResult.result.matchedCount;
|
|
259
|
-
result.modifiedCount += batchResult.result.modifiedCount;
|
|
260
|
-
result.batchCount++;
|
|
261
|
-
|
|
262
|
-
if (batchResult.attempts > 0) {
|
|
263
|
-
result.retries.push({
|
|
264
|
-
batchIndex: result.batchCount - 1,
|
|
265
|
-
attempts: batchResult.attempts,
|
|
266
|
-
success: true
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// 最后一批的进度回调
|
|
271
|
-
if (onProgress) {
|
|
272
|
-
onProgress({
|
|
273
|
-
currentBatch: result.batchCount,
|
|
274
|
-
matched: result.matchedCount,
|
|
275
|
-
modified: result.modifiedCount,
|
|
276
|
-
total: totalCount,
|
|
277
|
-
percentage: totalCount ? 100 : null,
|
|
278
|
-
errors: result.errors.length,
|
|
279
|
-
retries: result.retries.length
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
} catch (error) {
|
|
284
|
-
result.errors.push({
|
|
285
|
-
batchIndex: result.batchCount,
|
|
286
|
-
batchSize: batch.length,
|
|
287
|
-
error: error,
|
|
288
|
-
message: error.message
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// 7. 最终缓存失效
|
|
294
|
-
if (cache && result.modifiedCount > 0) {
|
|
295
|
-
try {
|
|
296
|
-
const ns = {
|
|
297
|
-
iid: instanceId,
|
|
298
|
-
type: 'mongodb',
|
|
299
|
-
db: databaseName,
|
|
300
|
-
collection: collectionName
|
|
301
|
-
};
|
|
302
|
-
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
303
|
-
|
|
304
|
-
// 检查是否在事务中
|
|
305
|
-
if (isInTransaction(options)) {
|
|
306
|
-
const tx = getTransactionFromSession(options.session);
|
|
307
|
-
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
308
|
-
await tx.recordInvalidation(pattern, {
|
|
309
|
-
operation: 'write',
|
|
310
|
-
query: filter || {},
|
|
311
|
-
collection: collectionName
|
|
312
|
-
});
|
|
313
|
-
logger.debug(`[updateBatch] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
314
|
-
} else {
|
|
315
|
-
const deleted = await cache.delPattern(pattern);
|
|
316
|
-
if (deleted > 0) {
|
|
317
|
-
logger.debug(`[updateBatch] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
} else {
|
|
321
|
-
const deleted = await cache.delPattern(pattern);
|
|
322
|
-
if (deleted > 0) {
|
|
323
|
-
logger.debug(`[updateBatch] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
} catch (cacheErr) {
|
|
327
|
-
logger.warn(`[updateBatch] 缓存失效失败: ${cacheErr.message}`);
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
// 8. 慢查询日志
|
|
332
|
-
const duration = Date.now() - startTime;
|
|
333
|
-
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
334
|
-
|
|
335
|
-
if (duration > slowQueryMs) {
|
|
336
|
-
logger.warn(`[updateBatch] 慢操作警告`, {
|
|
337
|
-
ns: `${databaseName}.${collectionName}`,
|
|
338
|
-
duration,
|
|
339
|
-
threshold: slowQueryMs,
|
|
340
|
-
updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators',
|
|
341
|
-
pipelineStages: isAggregation ? update.length : undefined,
|
|
342
|
-
totalCount,
|
|
343
|
-
matchedCount: result.matchedCount,
|
|
344
|
-
modifiedCount: result.modifiedCount,
|
|
345
|
-
batchCount: result.batchCount,
|
|
346
|
-
errorCount: result.errors.length,
|
|
347
|
-
retryCount: result.retries.length,
|
|
348
|
-
comment
|
|
349
|
-
});
|
|
350
|
-
} else {
|
|
351
|
-
logger.debug(`[updateBatch] 操作完成`, {
|
|
352
|
-
ns: `${databaseName}.${collectionName}`,
|
|
353
|
-
duration,
|
|
354
|
-
updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators',
|
|
355
|
-
matchedCount: result.matchedCount,
|
|
356
|
-
modifiedCount: result.modifiedCount,
|
|
357
|
-
batchCount: result.batchCount
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
resolve(result);
|
|
362
|
-
});
|
|
363
|
-
|
|
364
|
-
// 9. 监听流错误事件
|
|
365
|
-
stream.on('error', (error) => {
|
|
366
|
-
logger.error(`[updateBatch] 流式查询错误`, {
|
|
367
|
-
ns: `${databaseName}.${collectionName}`,
|
|
368
|
-
error: error.message,
|
|
369
|
-
code: error.code,
|
|
370
|
-
updateType: isAggregation ? 'aggregation-pipeline' : 'update-operators'
|
|
371
|
-
});
|
|
372
|
-
|
|
373
|
-
result.errors.push({
|
|
374
|
-
batchIndex: result.batchCount,
|
|
375
|
-
error: error,
|
|
376
|
-
message: `流式查询错误: ${error.message}`
|
|
377
|
-
});
|
|
378
|
-
|
|
379
|
-
// ✨ v1.0.8: 检测聚合管道不支持的错误(MongoDB 4.2+ 才支持)
|
|
380
|
-
if (isAggregation &&
|
|
381
|
-
(error.message.includes('pipeline') ||
|
|
382
|
-
error.message.includes('Unrecognized pipeline stage') ||
|
|
383
|
-
error.message.includes('The dollar ($) prefixed field') ||
|
|
384
|
-
error.code === 40324 ||
|
|
385
|
-
error.code === 9)) {
|
|
386
|
-
reject(createError(
|
|
387
|
-
ErrorCodes.UNSUPPORTED_OPERATION,
|
|
388
|
-
'MongoDB 4.2+ 才支持聚合管道更新。请升级 MongoDB 版本或使用传统更新操作符',
|
|
389
|
-
[{
|
|
390
|
-
field: 'update',
|
|
391
|
-
message: error.message,
|
|
392
|
-
requirement: 'MongoDB 4.2+',
|
|
393
|
-
currentError: error.code,
|
|
394
|
-
documentation: 'https://www.mongodb.com/docs/manual/tutorial/update-documents-with-aggregation-pipeline/'
|
|
395
|
-
}],
|
|
396
|
-
error
|
|
397
|
-
));
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
reject(createError(
|
|
402
|
-
ErrorCodes.WRITE_ERROR,
|
|
403
|
-
`updateBatch 流式查询失败: ${error.message}`,
|
|
404
|
-
null,
|
|
405
|
-
error
|
|
406
|
-
));
|
|
407
|
-
});
|
|
408
|
-
});
|
|
409
|
-
};
|
|
410
|
-
|
|
411
|
-
return { updateBatch };
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
module.exports = { createUpdateBatchOps };
|
|
415
|
-
|
|
416
|
-
|