monsqlize 1.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 +2474 -0
- package/LICENSE +21 -0
- package/README.md +1368 -0
- package/index.d.ts +1052 -0
- package/lib/cache.js +491 -0
- package/lib/common/cursor.js +58 -0
- package/lib/common/docs-urls.js +72 -0
- package/lib/common/index-options.js +222 -0
- package/lib/common/log.js +60 -0
- package/lib/common/namespace.js +21 -0
- package/lib/common/normalize.js +33 -0
- package/lib/common/page-result.js +42 -0
- package/lib/common/runner.js +56 -0
- package/lib/common/server-features.js +231 -0
- package/lib/common/shape-builders.js +26 -0
- package/lib/common/validation.js +49 -0
- package/lib/connect.js +76 -0
- package/lib/constants.js +54 -0
- package/lib/count-queue.js +187 -0
- package/lib/distributed-cache-invalidator.js +259 -0
- package/lib/errors.js +157 -0
- package/lib/index.js +352 -0
- package/lib/logger.js +224 -0
- package/lib/model/examples/test.js +114 -0
- package/lib/mongodb/common/accessor-helpers.js +44 -0
- package/lib/mongodb/common/agg-pipeline.js +32 -0
- package/lib/mongodb/common/iid.js +27 -0
- package/lib/mongodb/common/lexicographic-expr.js +52 -0
- package/lib/mongodb/common/shape.js +31 -0
- package/lib/mongodb/common/sort.js +38 -0
- package/lib/mongodb/common/transaction-aware.js +24 -0
- package/lib/mongodb/connect.js +178 -0
- package/lib/mongodb/index.js +458 -0
- package/lib/mongodb/management/admin-ops.js +199 -0
- package/lib/mongodb/management/bookmark-ops.js +166 -0
- package/lib/mongodb/management/cache-ops.js +49 -0
- package/lib/mongodb/management/collection-ops.js +386 -0
- package/lib/mongodb/management/database-ops.js +201 -0
- package/lib/mongodb/management/index-ops.js +474 -0
- package/lib/mongodb/management/index.js +16 -0
- package/lib/mongodb/management/namespace.js +30 -0
- package/lib/mongodb/management/validation-ops.js +267 -0
- package/lib/mongodb/queries/aggregate.js +133 -0
- package/lib/mongodb/queries/chain.js +623 -0
- package/lib/mongodb/queries/count.js +88 -0
- package/lib/mongodb/queries/distinct.js +68 -0
- package/lib/mongodb/queries/find-and-count.js +183 -0
- package/lib/mongodb/queries/find-by-ids.js +235 -0
- package/lib/mongodb/queries/find-one-by-id.js +170 -0
- package/lib/mongodb/queries/find-one.js +61 -0
- package/lib/mongodb/queries/find-page.js +565 -0
- package/lib/mongodb/queries/find.js +161 -0
- package/lib/mongodb/queries/index.js +49 -0
- package/lib/mongodb/writes/delete-many.js +181 -0
- package/lib/mongodb/writes/delete-one.js +173 -0
- package/lib/mongodb/writes/find-one-and-delete.js +193 -0
- package/lib/mongodb/writes/find-one-and-replace.js +222 -0
- package/lib/mongodb/writes/find-one-and-update.js +223 -0
- package/lib/mongodb/writes/increment-one.js +243 -0
- package/lib/mongodb/writes/index.js +41 -0
- package/lib/mongodb/writes/insert-batch.js +498 -0
- package/lib/mongodb/writes/insert-many.js +218 -0
- package/lib/mongodb/writes/insert-one.js +171 -0
- package/lib/mongodb/writes/replace-one.js +199 -0
- package/lib/mongodb/writes/result-handler.js +236 -0
- package/lib/mongodb/writes/update-many.js +205 -0
- package/lib/mongodb/writes/update-one.js +207 -0
- package/lib/mongodb/writes/upsert-one.js +190 -0
- package/lib/multi-level-cache.js +189 -0
- package/lib/operators.js +330 -0
- package/lib/redis-cache-adapter.js +237 -0
- package/lib/transaction/CacheLockManager.js +161 -0
- package/lib/transaction/DistributedCacheLockManager.js +239 -0
- package/lib/transaction/Transaction.js +314 -0
- package/lib/transaction/TransactionManager.js +266 -0
- package/lib/transaction/index.js +10 -0
- package/package.json +111 -0
|
@@ -0,0 +1,236 @@
|
|
|
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
|
+
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* updateMany 操作实现
|
|
3
|
+
* 更新所有匹配的文档
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { createError, ErrorCodes } = require("../../errors");
|
|
7
|
+
const CacheFactory = require("../../cache");
|
|
8
|
+
const { isInTransaction, getTransactionFromSession } = require("../common/transaction-aware");
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 创建 updateMany 操作
|
|
12
|
+
* @param {Object} context - 模块上下文
|
|
13
|
+
* @param {Object} context.db - MongoDB 数据库实例
|
|
14
|
+
* @param {Object} context.cache - 缓存实例
|
|
15
|
+
* @param {Object} context.logger - 日志实例
|
|
16
|
+
* @param {Object} context.defaults - 默认配置
|
|
17
|
+
* @param {string} context.collection - 集合名称
|
|
18
|
+
* @param {string} context.effectiveDbName - 数据库名称
|
|
19
|
+
* @param {string} context.instanceId - 实例ID
|
|
20
|
+
* @returns {Object} 包含 updateMany 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createUpdateManyOps(context) {
|
|
23
|
+
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
24
|
+
|
|
25
|
+
// 提取集合名称和原生 collection 对象
|
|
26
|
+
const collectionName = collection.collectionName;
|
|
27
|
+
const nativeCollection = collection;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 更新多个文档
|
|
31
|
+
* @param {Object} filter - 筛选条件(必需)
|
|
32
|
+
* @param {Object} update - 更新操作(必需,使用更新操作符如 $set)
|
|
33
|
+
* @param {Object} [options] - 操作选项
|
|
34
|
+
* @param {boolean} [options.upsert=false] - 不存在时是否插入
|
|
35
|
+
* @param {Object} [options.writeConcern] - 写关注选项
|
|
36
|
+
* @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
|
|
37
|
+
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
38
|
+
* @param {Object} [options.collation] - 排序规则
|
|
39
|
+
* @param {Array|Object} [options.arrayFilters] - 数组过滤器
|
|
40
|
+
* @param {Object} [options.hint] - 索引提示
|
|
41
|
+
* @returns {Promise<Object>} 更新结果 { acknowledged, matchedCount, modifiedCount, upsertedId?, upsertedCount? }
|
|
42
|
+
* @throws {Error} 当参数无效时
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* const result = await collection("users").updateMany(
|
|
46
|
+
* { status: "inactive" },
|
|
47
|
+
* { $set: { status: "archived", archivedAt: new Date() } }
|
|
48
|
+
* );
|
|
49
|
+
* console.log("Modified:", result.modifiedCount, "documents");
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* // 使用数组过滤器
|
|
53
|
+
* const result = await collection("users").updateMany(
|
|
54
|
+
* { "tags.name": "premium" },
|
|
55
|
+
* { $set: { "tags.$[elem].verified": true } },
|
|
56
|
+
* { arrayFilters: [{ "elem.name": "premium" }] }
|
|
57
|
+
* );
|
|
58
|
+
*/
|
|
59
|
+
const updateMany = async function updateMany(filter, update, options = {}) {
|
|
60
|
+
const startTime = Date.now();
|
|
61
|
+
|
|
62
|
+
// 1. 参数验证
|
|
63
|
+
if (!filter || typeof filter !== "object" || Array.isArray(filter)) {
|
|
64
|
+
throw createError(
|
|
65
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
66
|
+
"filter 必须是对象类型",
|
|
67
|
+
[{ field: "filter", type: "object.required", message: "filter 是必需参数且必须是对象" }]
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!update || typeof update !== "object" || Array.isArray(update)) {
|
|
72
|
+
throw createError(
|
|
73
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
74
|
+
"update 必须是对象类型",
|
|
75
|
+
[{ field: "update", type: "object.required", message: "update 是必需参数且必须是对象" }]
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 验证 update 包含更新操作符(防止整体替换)
|
|
80
|
+
const updateKeys = Object.keys(update);
|
|
81
|
+
if (updateKeys.length > 0 && !updateKeys.some(key => key.startsWith("$"))) {
|
|
82
|
+
throw createError(
|
|
83
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
84
|
+
"update 必须使用更新操作符(如 $set, $inc 等)",
|
|
85
|
+
[{ field: "update", type: "object.invalid", message: "请使用 $set, $inc, $push 等更新操作符" }]
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 2. 构建操作上下文
|
|
90
|
+
const operation = "updateMany";
|
|
91
|
+
const ns = `${databaseName}.${collectionName}`;
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
// 3. 执行更新操作
|
|
95
|
+
const result = await nativeCollection.updateMany(filter, update, options);
|
|
96
|
+
|
|
97
|
+
// 4. 自动失效缓存(只要有匹配,就失效缓存)
|
|
98
|
+
if (cache && result.matchedCount > 0) {
|
|
99
|
+
try {
|
|
100
|
+
// 使用标准命名空间模式删除该集合的所有缓存
|
|
101
|
+
const ns = {
|
|
102
|
+
iid: instanceId,
|
|
103
|
+
type: "mongodb",
|
|
104
|
+
db: databaseName,
|
|
105
|
+
collection: collectionName
|
|
106
|
+
};
|
|
107
|
+
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
108
|
+
|
|
109
|
+
// 检查是否在事务中
|
|
110
|
+
if (isInTransaction(options)) {
|
|
111
|
+
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
112
|
+
const tx = getTransactionFromSession(options.session);
|
|
113
|
+
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
114
|
+
// 🚀 传递 metadata 支持文档级别锁
|
|
115
|
+
await tx.recordInvalidation(pattern, {
|
|
116
|
+
operation: 'write',
|
|
117
|
+
query: filter,
|
|
118
|
+
collection: collectionName
|
|
119
|
+
});
|
|
120
|
+
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
121
|
+
} else {
|
|
122
|
+
const deleted = await cache.delPattern(pattern);
|
|
123
|
+
if (deleted > 0) {
|
|
124
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
} else {
|
|
128
|
+
// 非事务:直接失效缓存
|
|
129
|
+
const deleted = await cache.delPattern(pattern);
|
|
130
|
+
if (deleted > 0) {
|
|
131
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
} catch (cacheErr) {
|
|
135
|
+
// 缓存失效失败不影响写操作
|
|
136
|
+
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 5. 记录慢操作日志
|
|
141
|
+
const duration = Date.now() - startTime;
|
|
142
|
+
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
143
|
+
if (duration > slowQueryMs) {
|
|
144
|
+
logger.warn(`[${operation}] 慢操作警告`, {
|
|
145
|
+
ns,
|
|
146
|
+
duration,
|
|
147
|
+
threshold: slowQueryMs,
|
|
148
|
+
filterKeys: Object.keys(filter),
|
|
149
|
+
updateKeys: Object.keys(update),
|
|
150
|
+
matchedCount: result.matchedCount,
|
|
151
|
+
modifiedCount: result.modifiedCount,
|
|
152
|
+
upserted: result.upsertedId ? true : false,
|
|
153
|
+
comment: options.comment
|
|
154
|
+
});
|
|
155
|
+
} else {
|
|
156
|
+
logger.debug(`[${operation}] 操作完成`, {
|
|
157
|
+
ns,
|
|
158
|
+
duration,
|
|
159
|
+
matchedCount: result.matchedCount,
|
|
160
|
+
modifiedCount: result.modifiedCount,
|
|
161
|
+
upserted: result.upsertedId ? true : false
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return result;
|
|
166
|
+
|
|
167
|
+
} catch (error) {
|
|
168
|
+
// 6. 错误处理
|
|
169
|
+
const duration = Date.now() - startTime;
|
|
170
|
+
|
|
171
|
+
logger.error(`[${operation}] 操作失败`, {
|
|
172
|
+
ns,
|
|
173
|
+
duration,
|
|
174
|
+
error: error.message,
|
|
175
|
+
code: error.code,
|
|
176
|
+
filterKeys: Object.keys(filter),
|
|
177
|
+
updateKeys: Object.keys(update)
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// 识别特定错误类型
|
|
181
|
+
if (error.code === 11000) {
|
|
182
|
+
// MongoDB 重复键错误(可能在 upsert 时发生)
|
|
183
|
+
throw createError(
|
|
184
|
+
ErrorCodes.DUPLICATE_KEY,
|
|
185
|
+
"批量更新失败:违反唯一性约束",
|
|
186
|
+
[{ field: "_id", message: error.message }],
|
|
187
|
+
error
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// 其他错误
|
|
192
|
+
throw createError(
|
|
193
|
+
ErrorCodes.WRITE_ERROR,
|
|
194
|
+
`updateMany 操作失败: ${error.message}`,
|
|
195
|
+
null,
|
|
196
|
+
error
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
return { updateMany };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
module.exports = { createUpdateManyOps };
|
|
205
|
+
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* updateOne 操作实现
|
|
3
|
+
* 更新单个匹配的文档
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { createError, ErrorCodes } = require("../../errors");
|
|
7
|
+
const CacheFactory = require("../../cache");
|
|
8
|
+
const { isInTransaction, getTransactionFromSession } = require("../common/transaction-aware");
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 创建 updateOne 操作
|
|
12
|
+
* @param {Object} context - 模块上下文
|
|
13
|
+
* @param {Object} context.db - MongoDB 数据库实例
|
|
14
|
+
* @param {Object} context.cache - 缓存实例
|
|
15
|
+
* @param {Object} context.logger - 日志实例
|
|
16
|
+
* @param {Object} context.defaults - 默认配置
|
|
17
|
+
* @param {string} context.collection - 集合名称
|
|
18
|
+
* @param {string} context.effectiveDbName - 数据库名称
|
|
19
|
+
* @param {string} context.instanceId - 实例ID
|
|
20
|
+
* @returns {Object} 包含 updateOne 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createUpdateOneOps(context) {
|
|
23
|
+
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
24
|
+
|
|
25
|
+
// 提取集合名称和原生 collection 对象
|
|
26
|
+
const collectionName = collection.collectionName;
|
|
27
|
+
const nativeCollection = collection;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 更新单个文档
|
|
31
|
+
* @param {Object} filter - 筛选条件(必需)
|
|
32
|
+
* @param {Object} update - 更新操作(必需,使用更新操作符如 $set)
|
|
33
|
+
* @param {Object} [options] - 操作选项
|
|
34
|
+
* @param {boolean} [options.upsert=false] - 不存在时是否插入
|
|
35
|
+
* @param {Object} [options.writeConcern] - 写关注选项
|
|
36
|
+
* @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
|
|
37
|
+
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
38
|
+
* @param {Object} [options.collation] - 排序规则
|
|
39
|
+
* @param {Array|Object} [options.arrayFilters] - 数组过滤器
|
|
40
|
+
* @param {Object} [options.hint] - 索引提示
|
|
41
|
+
* @returns {Promise<Object>} 更新结果 { acknowledged, matchedCount, modifiedCount, upsertedId?, upsertedCount? }
|
|
42
|
+
* @throws {Error} 当参数无效时
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* const result = await collection("users").updateOne(
|
|
46
|
+
* { userId: "user123" },
|
|
47
|
+
* { $set: { status: "active", updatedAt: new Date() } }
|
|
48
|
+
* );
|
|
49
|
+
* console.log("Modified:", result.modifiedCount);
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* // 使用 upsert 选项
|
|
53
|
+
* const result = await collection("users").updateOne(
|
|
54
|
+
* { userId: "user123" },
|
|
55
|
+
* { $set: { name: "Alice", age: 25 } },
|
|
56
|
+
* { upsert: true }
|
|
57
|
+
* );
|
|
58
|
+
*/
|
|
59
|
+
const updateOne = async function updateOne(filter, update, options = {}) {
|
|
60
|
+
const startTime = Date.now();
|
|
61
|
+
|
|
62
|
+
// 1. 参数验证
|
|
63
|
+
if (!filter || typeof filter !== "object" || Array.isArray(filter)) {
|
|
64
|
+
throw createError(
|
|
65
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
66
|
+
"filter 必须是对象类型",
|
|
67
|
+
[{ field: "filter", type: "object.required", message: "filter 是必需参数且必须是对象" }]
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!update || typeof update !== "object" || Array.isArray(update)) {
|
|
72
|
+
throw createError(
|
|
73
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
74
|
+
"update 必须是对象类型",
|
|
75
|
+
[{ field: "update", type: "object.required", message: "update 是必需参数且必须是对象" }]
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 验证 update 包含更新操作符(防止整体替换)
|
|
80
|
+
const updateKeys = Object.keys(update);
|
|
81
|
+
if (updateKeys.length > 0 && !updateKeys.some(key => key.startsWith("$"))) {
|
|
82
|
+
throw createError(
|
|
83
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
84
|
+
"update 必须使用更新操作符(如 $set, $inc 等)",
|
|
85
|
+
[{ field: "update", type: "object.invalid", message: "请使用 $set, $inc, $push 等更新操作符,或使用 replaceOne 进行整体替换" }]
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 2. 构建操作上下文
|
|
90
|
+
const operation = "updateOne";
|
|
91
|
+
const ns = `${databaseName}.${collectionName}`;
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
// 3. 执行更新操作
|
|
95
|
+
const result = await nativeCollection.updateOne(filter, update, options);
|
|
96
|
+
|
|
97
|
+
// 4. 自动失效缓存
|
|
98
|
+
if (cache && result.modifiedCount > 0) {
|
|
99
|
+
try {
|
|
100
|
+
// 使用标准命名空间模式删除该集合的所有缓存
|
|
101
|
+
const ns = {
|
|
102
|
+
iid: instanceId,
|
|
103
|
+
type: "mongodb",
|
|
104
|
+
db: databaseName,
|
|
105
|
+
collection: collectionName
|
|
106
|
+
};
|
|
107
|
+
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
108
|
+
|
|
109
|
+
// 检查是否在事务中
|
|
110
|
+
if (isInTransaction(options)) {
|
|
111
|
+
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
112
|
+
// 这会立即失效缓存 + 添加缓存锁
|
|
113
|
+
const tx = getTransactionFromSession(options.session);
|
|
114
|
+
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
115
|
+
// 🚀 传递 metadata 支持文档级别锁和只读优化
|
|
116
|
+
await tx.recordInvalidation(pattern, {
|
|
117
|
+
operation: 'write',
|
|
118
|
+
query: filter,
|
|
119
|
+
collection: collectionName
|
|
120
|
+
});
|
|
121
|
+
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
122
|
+
} else {
|
|
123
|
+
// 降级处理:直接失效缓存
|
|
124
|
+
const deleted = await cache.delPattern(pattern);
|
|
125
|
+
if (deleted > 0) {
|
|
126
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} else {
|
|
130
|
+
// 非事务:直接失效缓存
|
|
131
|
+
const deleted = await cache.delPattern(pattern);
|
|
132
|
+
if (deleted > 0) {
|
|
133
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
} catch (cacheErr) {
|
|
137
|
+
// 缓存失效失败不影响写操作
|
|
138
|
+
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// 5. 记录慢操作日志
|
|
143
|
+
const duration = Date.now() - startTime;
|
|
144
|
+
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
145
|
+
if (duration > slowQueryMs) {
|
|
146
|
+
logger.warn(`[${operation}] 慢操作警告`, {
|
|
147
|
+
ns,
|
|
148
|
+
duration,
|
|
149
|
+
threshold: slowQueryMs,
|
|
150
|
+
filterKeys: Object.keys(filter),
|
|
151
|
+
updateKeys: Object.keys(update),
|
|
152
|
+
matchedCount: result.matchedCount,
|
|
153
|
+
modifiedCount: result.modifiedCount,
|
|
154
|
+
upserted: result.upsertedId ? true : false,
|
|
155
|
+
comment: options.comment
|
|
156
|
+
});
|
|
157
|
+
} else {
|
|
158
|
+
logger.debug(`[${operation}] 操作完成`, {
|
|
159
|
+
ns,
|
|
160
|
+
duration,
|
|
161
|
+
matchedCount: result.matchedCount,
|
|
162
|
+
modifiedCount: result.modifiedCount,
|
|
163
|
+
upserted: result.upsertedId ? true : false
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return result;
|
|
168
|
+
|
|
169
|
+
} catch (error) {
|
|
170
|
+
// 6. 错误处理
|
|
171
|
+
const duration = Date.now() - startTime;
|
|
172
|
+
|
|
173
|
+
logger.error(`[${operation}] 操作失败`, {
|
|
174
|
+
ns,
|
|
175
|
+
duration,
|
|
176
|
+
error: error.message,
|
|
177
|
+
code: error.code,
|
|
178
|
+
filterKeys: Object.keys(filter),
|
|
179
|
+
updateKeys: Object.keys(update)
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
// 识别特定错误类型
|
|
183
|
+
if (error.code === 11000) {
|
|
184
|
+
// MongoDB 重复键错误(可能在 upsert 时发生)
|
|
185
|
+
throw createError(
|
|
186
|
+
ErrorCodes.DUPLICATE_KEY,
|
|
187
|
+
"更新失败:违反唯一性约束",
|
|
188
|
+
[{ field: "_id", message: error.message }],
|
|
189
|
+
error
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 其他错误
|
|
194
|
+
throw createError(
|
|
195
|
+
ErrorCodes.WRITE_ERROR,
|
|
196
|
+
`updateOne 操作失败: ${error.message}`,
|
|
197
|
+
null,
|
|
198
|
+
error
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
return { updateOne };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = { createUpdateOneOps };
|
|
207
|
+
|