monsqlize 1.3.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +506 -235
  2. package/LICENSE +201 -21
  3. package/README.md +542 -928
  4. package/changelogs/README.md +163 -0
  5. package/changelogs/v2.0.0.md +222 -0
  6. package/changelogs/v2.0.1.md +39 -0
  7. package/dist/cjs/index.cjs +10788 -0
  8. package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
  9. package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
  10. package/dist/cjs/transaction/Transaction.cjs +158 -0
  11. package/dist/cjs/transaction/TransactionManager.cjs +298 -0
  12. package/dist/esm/index.mjs +10838 -0
  13. package/dist/types/base.d.ts +81 -0
  14. package/dist/types/collection.d.ts +1031 -0
  15. package/dist/types/expression.d.ts +115 -0
  16. package/dist/types/index.d.ts +23 -0
  17. package/dist/types/lock.d.ts +74 -0
  18. package/dist/types/model.d.ts +530 -0
  19. package/dist/types/mongodb.d.ts +49 -0
  20. package/dist/types/monsqlize.d.ts +491 -0
  21. package/dist/types/pool.d.ts +84 -0
  22. package/dist/types/runtime.d.ts +362 -0
  23. package/dist/types/saga.d.ts +143 -0
  24. package/dist/types/slow-query-log.d.ts +126 -0
  25. package/dist/types/sync.d.ts +103 -0
  26. package/dist/types/transaction.d.ts +132 -0
  27. package/package.json +120 -117
  28. package/index.d.ts +0 -1289
  29. package/lib/cache.js +0 -491
  30. package/lib/common/cursor.js +0 -58
  31. package/lib/common/docs-urls.js +0 -72
  32. package/lib/common/index-options.js +0 -222
  33. package/lib/common/log.js +0 -60
  34. package/lib/common/namespace.js +0 -21
  35. package/lib/common/normalize.js +0 -33
  36. package/lib/common/page-result.js +0 -42
  37. package/lib/common/runner.js +0 -56
  38. package/lib/common/server-features.js +0 -231
  39. package/lib/common/shape-builders.js +0 -26
  40. package/lib/common/validation.js +0 -112
  41. package/lib/connect.js +0 -76
  42. package/lib/constants.js +0 -54
  43. package/lib/count-queue.js +0 -187
  44. package/lib/distributed-cache-invalidator.js +0 -259
  45. package/lib/errors.js +0 -167
  46. package/lib/index.js +0 -461
  47. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -211
  48. package/lib/infrastructure/ssh-tunnel.js +0 -40
  49. package/lib/infrastructure/uri-parser.js +0 -35
  50. package/lib/lock/Lock.js +0 -66
  51. package/lib/lock/errors.js +0 -27
  52. package/lib/lock/index.js +0 -12
  53. package/lib/logger.js +0 -224
  54. package/lib/model/examples/test.js +0 -114
  55. package/lib/mongodb/common/accessor-helpers.js +0 -58
  56. package/lib/mongodb/common/agg-pipeline.js +0 -32
  57. package/lib/mongodb/common/iid.js +0 -27
  58. package/lib/mongodb/common/lexicographic-expr.js +0 -52
  59. package/lib/mongodb/common/shape.js +0 -31
  60. package/lib/mongodb/common/sort.js +0 -38
  61. package/lib/mongodb/common/transaction-aware.js +0 -24
  62. package/lib/mongodb/connect.js +0 -233
  63. package/lib/mongodb/index.js +0 -591
  64. package/lib/mongodb/management/admin-ops.js +0 -199
  65. package/lib/mongodb/management/bookmark-ops.js +0 -166
  66. package/lib/mongodb/management/cache-ops.js +0 -49
  67. package/lib/mongodb/management/collection-ops.js +0 -386
  68. package/lib/mongodb/management/database-ops.js +0 -201
  69. package/lib/mongodb/management/index-ops.js +0 -474
  70. package/lib/mongodb/management/index.js +0 -16
  71. package/lib/mongodb/management/namespace.js +0 -30
  72. package/lib/mongodb/management/validation-ops.js +0 -267
  73. package/lib/mongodb/queries/aggregate.js +0 -142
  74. package/lib/mongodb/queries/chain.js +0 -630
  75. package/lib/mongodb/queries/count.js +0 -98
  76. package/lib/mongodb/queries/distinct.js +0 -77
  77. package/lib/mongodb/queries/find-and-count.js +0 -192
  78. package/lib/mongodb/queries/find-by-ids.js +0 -235
  79. package/lib/mongodb/queries/find-one-by-id.js +0 -170
  80. package/lib/mongodb/queries/find-one.js +0 -70
  81. package/lib/mongodb/queries/find-page.js +0 -577
  82. package/lib/mongodb/queries/find.js +0 -170
  83. package/lib/mongodb/queries/index.js +0 -50
  84. package/lib/mongodb/queries/watch.js +0 -537
  85. package/lib/mongodb/writes/delete-many.js +0 -190
  86. package/lib/mongodb/writes/delete-one.js +0 -182
  87. package/lib/mongodb/writes/find-one-and-delete.js +0 -202
  88. package/lib/mongodb/writes/find-one-and-replace.js +0 -238
  89. package/lib/mongodb/writes/find-one-and-update.js +0 -239
  90. package/lib/mongodb/writes/increment-one.js +0 -252
  91. package/lib/mongodb/writes/index.js +0 -41
  92. package/lib/mongodb/writes/insert-batch.js +0 -507
  93. package/lib/mongodb/writes/insert-many.js +0 -227
  94. package/lib/mongodb/writes/insert-one.js +0 -180
  95. package/lib/mongodb/writes/replace-one.js +0 -215
  96. package/lib/mongodb/writes/result-handler.js +0 -236
  97. package/lib/mongodb/writes/update-many.js +0 -221
  98. package/lib/mongodb/writes/update-one.js +0 -223
  99. package/lib/mongodb/writes/upsert-one.js +0 -206
  100. package/lib/multi-level-cache.js +0 -189
  101. package/lib/operators.js +0 -330
  102. package/lib/redis-cache-adapter.js +0 -237
  103. package/lib/slow-query-log/base-storage.js +0 -69
  104. package/lib/slow-query-log/batch-queue.js +0 -96
  105. package/lib/slow-query-log/config-manager.js +0 -195
  106. package/lib/slow-query-log/index.js +0 -237
  107. package/lib/slow-query-log/mongodb-storage.js +0 -323
  108. package/lib/slow-query-log/query-hash.js +0 -38
  109. package/lib/transaction/CacheLockManager.js +0 -161
  110. package/lib/transaction/DistributedCacheLockManager.js +0 -474
  111. package/lib/transaction/Transaction.js +0 -314
  112. package/lib/transaction/TransactionManager.js +0 -266
  113. package/lib/transaction/index.js +0 -10
  114. package/lib/utils/objectid-converter.js +0 -566
@@ -1,227 +0,0 @@
1
- /**
2
- * insertMany 操作实现
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
-
11
- /**
12
- * 创建 insertMany 操作
13
- * @param {Object} context - 模块上下文
14
- * @param {Object} context.db - MongoDB 数据库实例
15
- * @param {Object} context.cache - 缓存实例
16
- * @param {Object} context.logger - 日志实例
17
- * @param {Object} context.defaults - 默认配置
18
- * @param {string} context.collection - 集合名称
19
- * @param {string} context.effectiveDbName - 数据库名称
20
- * @param {string} context.instanceId - 实例ID
21
- * @returns {Object} 包含 insertMany 方法的对象
22
- */
23
- function createInsertManyOps(context) {
24
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
25
-
26
- // 提取集合名称和原生 collection 对象
27
- const collectionName = collection.collectionName;
28
- const nativeCollection = collection;
29
-
30
- /**
31
- * 批量插入多个文档
32
- * @param {Array<Object>} documents - 要插入的文档数组(必需)
33
- * @param {Object} [options] - 操作选项
34
- * @param {boolean} [options.ordered=true] - 是否按顺序插入(遇到错误是否继续)
35
- * @param {Object} [options.writeConcern] - 写关注选项
36
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
37
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
38
- * @returns {Promise<Object>} 插入结果 { acknowledged, insertedCount, insertedIds }
39
- * @throws {Error} 当 documents 参数无效时
40
- *
41
- * @example
42
- * const result = await collection('users').insertMany([
43
- * { name: 'Alice', age: 25 },
44
- * { name: 'Bob', age: 30 }
45
- * ]);
46
- * console.log('Inserted count:', result.insertedCount);
47
- * console.log('Inserted IDs:', result.insertedIds);
48
- *
49
- * @example
50
- * // 使用 options 参数
51
- * const result = await collection('users').insertMany(
52
- * [
53
- * { name: 'Charlie', age: 35 },
54
- * { name: 'David', age: 40 }
55
- * ],
56
- * { ordered: false, comment: 'batch insert' }
57
- * );
58
- */
59
- const insertMany = async function insertMany(documents, options = {}) {
60
- const startTime = Date.now();
61
-
62
- // 1. 参数验证
63
- if (!Array.isArray(documents)) {
64
- throw createError(
65
- ErrorCodes.DOCUMENTS_REQUIRED,
66
- 'documents 必须是数组类型',
67
- [{ field: 'documents', type: 'array.required', message: 'documents 是必需参数且必须是数组' }]
68
- );
69
- }
70
-
71
- if (documents.length === 0) {
72
- throw createError(
73
- ErrorCodes.DOCUMENTS_REQUIRED,
74
- 'documents 数组不能为空',
75
- [{ field: 'documents', type: 'array.min', message: 'documents 至少需要包含一个文档' }]
76
- );
77
- }
78
-
79
- // 验证每个文档都是对象
80
- const invalidDocs = documents.filter((doc, index) => {
81
- return !doc || typeof doc !== 'object' || Array.isArray(doc);
82
- });
83
-
84
- if (invalidDocs.length > 0) {
85
- throw createError(
86
- ErrorCodes.DOCUMENTS_REQUIRED,
87
- 'documents 中的所有元素必须是对象类型',
88
- invalidDocs.map((doc, idx) => ({
89
- field: `documents[${idx}]`,
90
- type: 'object.required',
91
- message: '必须是对象类型'
92
- }))
93
- );
94
- }
95
-
96
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
97
- const convertedDocuments = documents.map(doc => convertObjectIdStrings(doc, 'document', 0, new WeakSet(), {
98
- logger: context.logger,
99
- excludeFields: context.autoConvertConfig?.excludeFields,
100
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
101
- maxDepth: context.autoConvertConfig?.maxDepth
102
- }));
103
-
104
- // 2. 构建操作上下文
105
- const operation = 'insertMany';
106
- const ns = `${databaseName}.${collectionName}`;
107
- const docCount = documents.length;
108
-
109
- try {
110
- // 3. 执行批量插入操作
111
- const result = await nativeCollection.insertMany(convertedDocuments, options);
112
-
113
- // 4. 自动失效缓存
114
- if (cache) {
115
- try {
116
- // 使用标准命名空间模式删除该集合的所有缓存
117
- const nsObj = {
118
- iid: instanceId,
119
- type: 'mongodb',
120
- db: databaseName,
121
- collection: collectionName
122
- };
123
- const pattern = CacheFactory.buildNamespacePattern(nsObj);
124
-
125
- // 检查是否在事务中
126
- if (isInTransaction(options)) {
127
- // 事务中:调用 Transaction 的 recordInvalidation 方法
128
- const tx = getTransactionFromSession(options.session);
129
- if (tx && typeof tx.recordInvalidation === 'function') {
130
- // 🚀 传递 metadata 支持文档级别锁
131
- await tx.recordInvalidation(pattern, {
132
- operation: 'write',
133
- query: {},
134
- collection: collectionName
135
- });
136
- logger.debug(`[${operation}] 事务中失效缓存: ${nsObj.db}.${nsObj.collection}`);
137
- } else {
138
- const deleted = await cache.delPattern(pattern);
139
- if (deleted > 0) {
140
- logger.debug(`[${operation}] 自动失效缓存: ${nsObj.db}.${nsObj.collection}, 删除 ${deleted} 个缓存键`);
141
- }
142
- }
143
- } else {
144
- // 非事务:直接失效缓存
145
- const deleted = await cache.delPattern(pattern);
146
- if (deleted > 0) {
147
- logger.debug(`[${operation}] 自动失效缓存: ${nsObj.db}.${nsObj.collection}, 删除 ${deleted} 个缓存键`);
148
- }
149
- }
150
- } catch (cacheErr) {
151
- // 缓存失效失败不影响写操作
152
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
153
- }
154
- }
155
-
156
- // 5. 记录慢操作日志
157
- const duration = Date.now() - startTime;
158
- const slowQueryMs = defaults.slowQueryMs ?? 1000;
159
- if (duration > slowQueryMs) {
160
- logger.warn(`[${operation}] 慢操作警告`, {
161
- ns,
162
- duration,
163
- threshold: slowQueryMs,
164
- documentCount: docCount,
165
- insertedCount: result.insertedCount,
166
- ordered: options.ordered !== false,
167
- comment: options.comment
168
- });
169
- } else {
170
- logger.debug(`[${operation}] 操作完成`, {
171
- ns,
172
- duration,
173
- documentCount: docCount,
174
- insertedCount: result.insertedCount
175
- });
176
- }
177
-
178
- return result;
179
-
180
- } catch (error) {
181
- // 6. 错误处理
182
- const duration = Date.now() - startTime;
183
-
184
- logger.error(`[${operation}] 操作失败`, {
185
- ns,
186
- duration,
187
- error: error.message,
188
- code: error.code,
189
- documentCount: docCount,
190
- ordered: options.ordered !== false
191
- });
192
-
193
- // 识别特定错误类型
194
- if (error.code === 11000) {
195
- // MongoDB 重复键错误
196
- throw createError(
197
- ErrorCodes.DUPLICATE_KEY,
198
- '批量插入失败:违反唯一性约束',
199
- [{ message: error.message, writeErrors: error.writeErrors }],
200
- error
201
- );
202
- }
203
-
204
- // 部分成功的情况(ordered=false 时可能发生)
205
- if (error.result && error.result.insertedCount > 0) {
206
- logger.warn(`[${operation}] 部分成功`, {
207
- ns,
208
- insertedCount: error.result.insertedCount,
209
- totalCount: docCount,
210
- failedCount: docCount - error.result.insertedCount
211
- });
212
- }
213
-
214
- // 其他错误
215
- throw createError(
216
- ErrorCodes.WRITE_ERROR,
217
- `insertMany 操作失败: ${error.message}`,
218
- error.writeErrors || null,
219
- error
220
- );
221
- }
222
- };
223
-
224
- return { insertMany };
225
- }
226
-
227
- module.exports = { createInsertManyOps };
@@ -1,180 +0,0 @@
1
- /**
2
- * insertOne 操作实现
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
-
11
- /**
12
- * 创建 insertOne 操作
13
- * @param {Object} context - 模块上下文
14
- * @param {Object} context.db - MongoDB 数据库实例
15
- * @param {Object} context.cache - 缓存实例
16
- * @param {Object} context.logger - 日志实例
17
- * @param {Object} context.defaults - 默认配置
18
- * @param {string} context.collectionName - 集合名称
19
- * @param {string} context.databaseName - 数据库名称
20
- * @param {string} context.instanceId - 实例ID
21
- * @returns {Object} 包含 insertOne 方法的对象
22
- */
23
- function createInsertOneOps(context) {
24
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
25
-
26
- // 提取集合名称和原生 collection 对象
27
- const collectionName = collection.collectionName;
28
- const nativeCollection = collection;
29
-
30
- /**
31
- * 插入单个文档
32
- * @param {Object} document - 要插入的文档(必需)
33
- * @param {Object} [options] - 操作选项
34
- * @param {Object} [options.writeConcern] - 写关注选项
35
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
36
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
37
- * @returns {Promise<Object>} 插入结果 { acknowledged, insertedId }
38
- * @throws {Error} 当 document 参数无效时
39
- *
40
- * @example
41
- * const result = await collection('users').insertOne(
42
- * { name: 'Alice', age: 25 }
43
- * );
44
- * console.log('Inserted ID:', result.insertedId);
45
- *
46
- * @example
47
- * // 使用 options 参数
48
- * const result = await collection('users').insertOne(
49
- * { name: 'Bob', age: 30 },
50
- * { bypassDocumentValidation: true, comment: 'test insert' }
51
- * );
52
- */
53
- const insertOne = async function insertOne(document, options = {}) {
54
- const startTime = Date.now();
55
-
56
- // 1. 参数验证
57
- if (!document || typeof document !== 'object' || Array.isArray(document)) {
58
- throw createError(
59
- ErrorCodes.DOCUMENT_REQUIRED,
60
- 'document 必须是对象类型',
61
- [{ field: 'document', type: 'object.required', message: 'document 是必需参数且必须是对象' }]
62
- );
63
- }
64
-
65
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
66
- const convertedDocument = convertObjectIdStrings(document, 'document', 0, new WeakSet(), {
67
- logger: context.logger,
68
- excludeFields: context.autoConvertConfig?.excludeFields,
69
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
70
- maxDepth: context.autoConvertConfig?.maxDepth
71
- });
72
-
73
- // 2. 构建操作上下文
74
- const operation = 'insertOne';
75
- const ns = `${databaseName}.${collectionName}`;
76
-
77
- try {
78
- // 3. 执行插入操作
79
- const result = await nativeCollection.insertOne(convertedDocument, options);
80
-
81
- // 4. 自动失效缓存
82
- if (cache) {
83
- try {
84
- // 使用标准命名空间模式删除该集合的所有缓存
85
- const ns = {
86
- iid: instanceId,
87
- type: 'mongodb',
88
- db: databaseName,
89
- collection: collectionName
90
- };
91
- const pattern = CacheFactory.buildNamespacePattern(ns);
92
-
93
- // 检查是否在事务中
94
- if (isInTransaction(options)) {
95
- // 事务中:调用 Transaction 的 recordInvalidation 方法
96
- const tx = getTransactionFromSession(options.session);
97
- if (tx && typeof tx.recordInvalidation === 'function') {
98
- // 🚀 传递 metadata 支持文档级别锁
99
- await tx.recordInvalidation(pattern, {
100
- operation: 'write',
101
- query: { _id: result.insertedId },
102
- collection: collectionName
103
- });
104
- logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
105
- } else {
106
- const deleted = await cache.delPattern(pattern);
107
- if (deleted > 0) {
108
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
109
- }
110
- }
111
- } else {
112
- // 非事务:直接失效缓存
113
- const deleted = await cache.delPattern(pattern);
114
- if (deleted > 0) {
115
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
116
- }
117
- }
118
- } catch (cacheErr) {
119
- // 缓存失效失败不影响写操作
120
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
121
- }
122
- }
123
-
124
- // 5. 记录慢操作日志
125
- const duration = Date.now() - startTime;
126
- const slowQueryMs = defaults.slowQueryMs || 1000;
127
- if (duration > slowQueryMs) {
128
- logger.warn(`[${operation}] 慢操作警告`, {
129
- ns,
130
- duration,
131
- threshold: slowQueryMs,
132
- documentKeys: Object.keys(document),
133
- insertedId: result.insertedId,
134
- comment: options.comment
135
- });
136
- } else {
137
- logger.debug(`[${operation}] 操作完成`, {
138
- ns,
139
- duration,
140
- insertedId: result.insertedId
141
- });
142
- }
143
-
144
- return result;
145
-
146
- } catch (error) {
147
- // 6. 错误处理
148
- const duration = Date.now() - startTime;
149
-
150
- logger.error(`[${operation}] 操作失败`, {
151
- ns,
152
- duration,
153
- error: error.message,
154
- code: error.code,
155
- documentKeys: Object.keys(document)
156
- });
157
-
158
- // 识别特定错误类型
159
- if (error.code === 11000) {
160
- // MongoDB 重复键错误
161
- throw createError(
162
- ErrorCodes.DUPLICATE_KEY,
163
- '文档插入失败:违反唯一性约束',
164
- [{ field: '_id', message: error.message }],
165
- error
166
- );
167
- }
168
-
169
- // 其他错误
170
- throw createError(
171
- ErrorCodes.WRITE_ERROR,
172
- `insertOne 操作失败: ${error.message}`,
173
- null,
174
- error
175
- );
176
- }
177
- };
178
-
179
- return { insertOne };
180
- } module.exports = { createInsertOneOps };
@@ -1,215 +0,0 @@
1
- /**
2
- * replaceOne 操作实现
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
-
11
- /**
12
- * 创建 replaceOne 操作
13
- * @param {Object} context - 模块上下文
14
- * @param {Object} context.db - MongoDB 数据库实例
15
- * @param {Object} context.cache - 缓存实例
16
- * @param {Object} context.logger - 日志实例
17
- * @param {Object} context.defaults - 默认配置
18
- * @param {string} context.collection - 集合名称
19
- * @param {string} context.effectiveDbName - 数据库名称
20
- * @param {string} context.instanceId - 实例ID
21
- * @returns {Object} 包含 replaceOne 方法的对象
22
- */
23
- function createReplaceOneOps(context) {
24
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
25
-
26
- // 提取集合名称和原生 collection 对象
27
- const collectionName = collection.collectionName;
28
- const nativeCollection = collection;
29
-
30
- /**
31
- * 替换单个文档(完整替换,不使用更新操作符)
32
- * @param {Object} filter - 筛选条件(必需)
33
- * @param {Object} replacement - 替换文档(必需,不能包含更新操作符)
34
- * @param {Object} [options] - 操作选项
35
- * @param {boolean} [options.upsert=false] - 不存在时是否插入
36
- * @param {Object} [options.writeConcern] - 写关注选项
37
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
38
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
39
- * @param {Object} [options.collation] - 排序规则
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").replaceOne(
46
- * { userId: "user123" },
47
- * { userId: "user123", name: "Alice", age: 25, status: "active" }
48
- * );
49
- * console.log("Modified:", result.modifiedCount);
50
- *
51
- * @example
52
- * // 使用 upsert 选项
53
- * const result = await collection("users").replaceOne(
54
- * { userId: "user456" },
55
- * { userId: "user456", name: "Bob", age: 30 },
56
- * { upsert: true }
57
- * );
58
- */
59
- const replaceOne = async function replaceOne(filter, replacement, 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 (!replacement || typeof replacement !== 'object' || Array.isArray(replacement)) {
72
- throw createError(
73
- ErrorCodes.INVALID_ARGUMENT,
74
- 'replacement 必须是对象类型',
75
- [{ field: 'replacement', type: 'object.required', message: 'replacement 是必需参数且必须是对象' }]
76
- );
77
- }
78
-
79
- // 验证 replacement 不包含更新操作符(防止误用)
80
- const replacementKeys = Object.keys(replacement);
81
- if (replacementKeys.some(key => key.startsWith('$'))) {
82
- throw createError(
83
- ErrorCodes.INVALID_ARGUMENT,
84
- 'replacement 不能包含更新操作符(如 $set, $inc 等)',
85
- [{ field: 'replacement', type: 'object.invalid', message: 'replaceOne 用于完整替换文档,请使用 updateOne 进行部分更新' }]
86
- );
87
- }
88
-
89
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
90
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
91
- logger: context.logger,
92
- excludeFields: context.autoConvertConfig?.excludeFields,
93
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
94
- maxDepth: context.autoConvertConfig?.maxDepth
95
- });
96
-
97
- const convertedReplacement = convertObjectIdStrings(replacement, 'document', 0, new WeakSet(), {
98
- logger: context.logger,
99
- excludeFields: context.autoConvertConfig?.excludeFields,
100
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
101
- maxDepth: context.autoConvertConfig?.maxDepth
102
- });
103
-
104
- // 2. 构建操作上下文
105
- const operation = 'replaceOne';
106
- const ns = `${databaseName}.${collectionName}`;
107
-
108
- try {
109
- // 3. 执行替换操作
110
- const result = await nativeCollection.replaceOne(convertedFilter, convertedReplacement, options);
111
-
112
- // 4. 自动失效缓存
113
- if (cache && result.modifiedCount > 0) {
114
- try {
115
- // 使用标准命名空间模式删除该集合的所有缓存
116
- const ns = {
117
- iid: instanceId,
118
- type: 'mongodb',
119
- db: databaseName,
120
- collection: collectionName
121
- };
122
- const pattern = CacheFactory.buildNamespacePattern(ns);
123
-
124
- // 检查是否在事务中
125
- if (isInTransaction(options)) {
126
- // 事务中:调用 Transaction 的 recordInvalidation 方法
127
- const tx = getTransactionFromSession(options.session);
128
- if (tx && typeof tx.recordInvalidation === 'function') {
129
- await tx.recordInvalidation(pattern);
130
- logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
131
- } else {
132
- const deleted = await cache.delPattern(pattern);
133
- if (deleted > 0) {
134
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
135
- }
136
- }
137
- } else {
138
- // 非事务:直接失效缓存
139
- const deleted = await cache.delPattern(pattern);
140
- if (deleted > 0) {
141
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
142
- }
143
- }
144
- } catch (cacheErr) {
145
- // 缓存失效失败不影响写操作
146
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
147
- }
148
- }
149
-
150
- // 5. 记录慢操作日志
151
- const duration = Date.now() - startTime;
152
- const slowQueryMs = defaults.slowQueryMs || 1000;
153
- if (duration > slowQueryMs) {
154
- logger.warn(`[${operation}] 慢操作警告`, {
155
- ns,
156
- duration,
157
- threshold: slowQueryMs,
158
- filterKeys: Object.keys(filter),
159
- replacementKeys: Object.keys(replacement),
160
- matchedCount: result.matchedCount,
161
- modifiedCount: result.modifiedCount,
162
- upserted: result.upsertedId ? true : false,
163
- comment: options.comment
164
- });
165
- } else {
166
- logger.debug(`[${operation}] 操作完成`, {
167
- ns,
168
- duration,
169
- matchedCount: result.matchedCount,
170
- modifiedCount: result.modifiedCount,
171
- upserted: result.upsertedId ? true : false
172
- });
173
- }
174
-
175
- return result;
176
-
177
- } catch (error) {
178
- // 6. 错误处理
179
- const duration = Date.now() - startTime;
180
-
181
- logger.error(`[${operation}] 操作失败`, {
182
- ns,
183
- duration,
184
- error: error.message,
185
- code: error.code,
186
- filterKeys: Object.keys(filter),
187
- replacementKeys: Object.keys(replacement)
188
- });
189
-
190
- // 识别特定错误类型
191
- if (error.code === 11000) {
192
- // MongoDB 重复键错误(可能在 upsert 时发生)
193
- throw createError(
194
- ErrorCodes.DUPLICATE_KEY,
195
- '替换失败:违反唯一性约束',
196
- [{ field: '_id', message: error.message }],
197
- error
198
- );
199
- }
200
-
201
- // 其他错误
202
- throw createError(
203
- ErrorCodes.WRITE_ERROR,
204
- `replaceOne 操作失败: ${error.message}`,
205
- null,
206
- error
207
- );
208
- }
209
- };
210
-
211
- return { replaceOne };
212
- }
213
-
214
- module.exports = { createReplaceOneOps };
215
-