@yandjin-mikro-orm/mongodb 6.1.4-rc-sti-changes-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.
- package/LICENSE +21 -0
- package/MongoConnection.d.ts +51 -0
- package/MongoConnection.js +368 -0
- package/MongoDriver.d.ts +29 -0
- package/MongoDriver.js +315 -0
- package/MongoEntityManager.d.ts +26 -0
- package/MongoEntityManager.js +38 -0
- package/MongoEntityRepository.d.ts +16 -0
- package/MongoEntityRepository.js +27 -0
- package/MongoExceptionConverter.d.ts +7 -0
- package/MongoExceptionConverter.js +20 -0
- package/MongoMikroORM.d.ts +19 -0
- package/MongoMikroORM.js +29 -0
- package/MongoPlatform.d.ts +28 -0
- package/MongoPlatform.js +82 -0
- package/MongoSchemaGenerator.d.ts +32 -0
- package/MongoSchemaGenerator.js +215 -0
- package/README.md +383 -0
- package/index.d.ts +11 -0
- package/index.js +34 -0
- package/index.mjs +199 -0
- package/package.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 Martin Adámek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { MongoClient, type ClientSession, type Collection, type Db, type MongoClientOptions, type TransactionOptions } from "mongodb";
|
|
2
|
+
import { Connection, type AnyEntity, type Configuration, type ConnectionConfig, type ConnectionOptions, type ConnectionType, type EntityData, type EntityName, type FilterQuery, type IsolationLevel, type QueryOrderMap, type QueryResult, type Transaction, type TransactionEventBroadcaster, type UpsertOptions, type UpsertManyOptions, type LoggingOptions } from "@yandjin-mikro-orm/core";
|
|
3
|
+
export declare class MongoConnection extends Connection {
|
|
4
|
+
protected client: MongoClient;
|
|
5
|
+
protected db: Db;
|
|
6
|
+
constructor(config: Configuration, options?: ConnectionOptions, type?: ConnectionType);
|
|
7
|
+
connect(): Promise<void>;
|
|
8
|
+
close(force?: boolean): Promise<void>;
|
|
9
|
+
isConnected(): Promise<boolean>;
|
|
10
|
+
checkConnection(): Promise<{
|
|
11
|
+
ok: boolean;
|
|
12
|
+
reason?: string;
|
|
13
|
+
error?: Error;
|
|
14
|
+
}>;
|
|
15
|
+
getClient(): MongoClient;
|
|
16
|
+
getCollection<T extends object>(name: EntityName<T>): Collection<T>;
|
|
17
|
+
createCollection<T extends object>(name: EntityName<T>): Promise<Collection<T>>;
|
|
18
|
+
listCollections(): Promise<string[]>;
|
|
19
|
+
dropCollection(name: EntityName<AnyEntity>): Promise<boolean>;
|
|
20
|
+
getDefaultClientUrl(): string;
|
|
21
|
+
getConnectionOptions(): MongoClientOptions & ConnectionConfig;
|
|
22
|
+
getClientUrl(): string;
|
|
23
|
+
getDb(): Db;
|
|
24
|
+
execute(query: string): Promise<any>;
|
|
25
|
+
find<T extends object>(collection: string, where: FilterQuery<T>, orderBy?: QueryOrderMap<T> | QueryOrderMap<T>[], limit?: number, offset?: number, fields?: string[], ctx?: Transaction<ClientSession>, loggerContext?: LoggingOptions): Promise<EntityData<T>[]>;
|
|
26
|
+
insertOne<T extends object>(collection: string, data: Partial<T>, ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
|
|
27
|
+
insertMany<T extends object>(collection: string, data: Partial<T>[], ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
|
|
28
|
+
updateMany<T extends object>(collection: string, where: FilterQuery<T>, data: Partial<T>, ctx?: Transaction<ClientSession>, upsert?: boolean, upsertOptions?: UpsertOptions<T>): Promise<QueryResult<T>>;
|
|
29
|
+
bulkUpdateMany<T extends object>(collection: string, where: FilterQuery<T>[], data: Partial<T>[], ctx?: Transaction<ClientSession>, upsert?: boolean, upsertOptions?: UpsertManyOptions<T>): Promise<QueryResult<T>>;
|
|
30
|
+
deleteMany<T extends object>(collection: string, where: FilterQuery<T>, ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
|
|
31
|
+
aggregate<T extends object = any>(collection: string, pipeline: any[], ctx?: Transaction<ClientSession>, loggerContext?: LoggingOptions): Promise<T[]>;
|
|
32
|
+
countDocuments<T extends object>(collection: string, where: FilterQuery<T>, ctx?: Transaction<ClientSession>): Promise<number>;
|
|
33
|
+
transactional<T>(cb: (trx: Transaction<ClientSession>) => Promise<T>, options?: {
|
|
34
|
+
isolationLevel?: IsolationLevel;
|
|
35
|
+
ctx?: Transaction<ClientSession>;
|
|
36
|
+
eventBroadcaster?: TransactionEventBroadcaster;
|
|
37
|
+
} & TransactionOptions): Promise<T>;
|
|
38
|
+
begin(options?: {
|
|
39
|
+
isolationLevel?: IsolationLevel;
|
|
40
|
+
ctx?: ClientSession;
|
|
41
|
+
eventBroadcaster?: TransactionEventBroadcaster;
|
|
42
|
+
} & TransactionOptions): Promise<ClientSession>;
|
|
43
|
+
commit(ctx: ClientSession, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
|
|
44
|
+
rollback(ctx: ClientSession, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
|
|
45
|
+
private runQuery;
|
|
46
|
+
private rethrow;
|
|
47
|
+
private createUpdatePayload;
|
|
48
|
+
private transformResult;
|
|
49
|
+
private getCollectionName;
|
|
50
|
+
private logObject;
|
|
51
|
+
}
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MongoConnection = void 0;
|
|
4
|
+
const mongodb_1 = require("mongodb");
|
|
5
|
+
const bson_1 = require("bson");
|
|
6
|
+
const util_1 = require("util");
|
|
7
|
+
const core_1 = require("@yandjin-mikro-orm/core");
|
|
8
|
+
class MongoConnection extends core_1.Connection {
|
|
9
|
+
client;
|
|
10
|
+
db;
|
|
11
|
+
constructor(config, options, type = "write") {
|
|
12
|
+
super(config, options, type);
|
|
13
|
+
// @ts-ignore
|
|
14
|
+
bson_1.ObjectId.prototype[util_1.inspect.custom] = function () {
|
|
15
|
+
return `ObjectId('${this.toHexString()}')`;
|
|
16
|
+
};
|
|
17
|
+
// @ts-ignore
|
|
18
|
+
Date.prototype[util_1.inspect.custom] = function () {
|
|
19
|
+
return `ISODate('${this.toISOString()}')`;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
async connect() {
|
|
23
|
+
const driverOptions = this.config.get("driverOptions");
|
|
24
|
+
if (driverOptions instanceof mongodb_1.MongoClient) {
|
|
25
|
+
this.logger.log("info", "Reusing MongoClient provided via `driverOptions`");
|
|
26
|
+
this.client = driverOptions;
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
this.client = new mongodb_1.MongoClient(this.config.getClientUrl(), this.getConnectionOptions());
|
|
30
|
+
await this.client.connect();
|
|
31
|
+
}
|
|
32
|
+
this.db = this.client.db(this.config.get("dbName"));
|
|
33
|
+
this.connected = true;
|
|
34
|
+
}
|
|
35
|
+
async close(force) {
|
|
36
|
+
await this.client?.close(!!force);
|
|
37
|
+
this.connected = false;
|
|
38
|
+
}
|
|
39
|
+
async isConnected() {
|
|
40
|
+
try {
|
|
41
|
+
const res = await this.db?.command({ ping: 1 });
|
|
42
|
+
return (this.connected = !!res.ok);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
return (this.connected = false);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async checkConnection() {
|
|
49
|
+
try {
|
|
50
|
+
const res = await this.db?.command({ ping: 1 });
|
|
51
|
+
return { ok: !!res.ok };
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
return { ok: false, reason: error.message, error };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
getClient() {
|
|
58
|
+
return this.client;
|
|
59
|
+
}
|
|
60
|
+
getCollection(name) {
|
|
61
|
+
return this.db.collection(this.getCollectionName(name));
|
|
62
|
+
}
|
|
63
|
+
async createCollection(name) {
|
|
64
|
+
return this.db.createCollection(this.getCollectionName(name));
|
|
65
|
+
}
|
|
66
|
+
async listCollections() {
|
|
67
|
+
const collections = await this.db
|
|
68
|
+
.listCollections({}, { nameOnly: true })
|
|
69
|
+
.toArray();
|
|
70
|
+
return collections.map((c) => c.name);
|
|
71
|
+
}
|
|
72
|
+
async dropCollection(name) {
|
|
73
|
+
return this.db.dropCollection(this.getCollectionName(name));
|
|
74
|
+
}
|
|
75
|
+
getDefaultClientUrl() {
|
|
76
|
+
return "mongodb://127.0.0.1:27017";
|
|
77
|
+
}
|
|
78
|
+
getConnectionOptions() {
|
|
79
|
+
const ret = {};
|
|
80
|
+
const pool = this.config.get("pool");
|
|
81
|
+
const username = this.config.get("user");
|
|
82
|
+
const password = this.config.get("password");
|
|
83
|
+
if (this.config.get("host")) {
|
|
84
|
+
throw new core_1.ValidationError("Mongo driver does not support `host` options, use `clientUrl` instead!");
|
|
85
|
+
}
|
|
86
|
+
if (username && password) {
|
|
87
|
+
ret.auth = { username, password };
|
|
88
|
+
}
|
|
89
|
+
if (pool.min) {
|
|
90
|
+
ret.minPoolSize = pool.min;
|
|
91
|
+
}
|
|
92
|
+
if (pool.max) {
|
|
93
|
+
ret.maxPoolSize = pool.max;
|
|
94
|
+
}
|
|
95
|
+
return core_1.Utils.mergeConfig(ret, this.config.get("driverOptions"));
|
|
96
|
+
}
|
|
97
|
+
getClientUrl() {
|
|
98
|
+
const options = this.getConnectionOptions();
|
|
99
|
+
const clientUrl = this.config.getClientUrl(true);
|
|
100
|
+
const match = clientUrl.match(/^(\w+):\/\/((.*@.+)|.+)$/);
|
|
101
|
+
return match
|
|
102
|
+
? `${match[1]}://${options.auth ? options.auth.username + ":*****@" : ""}${match[2]}`
|
|
103
|
+
: clientUrl;
|
|
104
|
+
}
|
|
105
|
+
getDb() {
|
|
106
|
+
return this.db;
|
|
107
|
+
}
|
|
108
|
+
async execute(query) {
|
|
109
|
+
throw new Error(`${this.constructor.name} does not support generic execute method`);
|
|
110
|
+
}
|
|
111
|
+
async find(collection, where, orderBy, limit, offset, fields, ctx, loggerContext) {
|
|
112
|
+
await this.ensureConnection();
|
|
113
|
+
collection = this.getCollectionName(collection);
|
|
114
|
+
const options = ctx ? { session: ctx } : {};
|
|
115
|
+
if (fields) {
|
|
116
|
+
options.projection = fields.reduce((o, k) => ({ ...o, [k]: 1 }), {});
|
|
117
|
+
}
|
|
118
|
+
const resultSet = this.getCollection(collection).find(where, options);
|
|
119
|
+
let query = `db.getCollection('${collection}').find(${this.logObject(where)}, ${this.logObject(options)})`;
|
|
120
|
+
orderBy = core_1.Utils.asArray(orderBy);
|
|
121
|
+
if (Array.isArray(orderBy) && orderBy.length > 0) {
|
|
122
|
+
const orderByTuples = [];
|
|
123
|
+
orderBy.forEach((o) => {
|
|
124
|
+
core_1.Utils.keys(o).forEach((k) => {
|
|
125
|
+
const direction = o[k];
|
|
126
|
+
orderByTuples.push([
|
|
127
|
+
k.toString(),
|
|
128
|
+
core_1.Utils.isString(direction)
|
|
129
|
+
? direction.toUpperCase() === core_1.QueryOrder.ASC
|
|
130
|
+
? 1
|
|
131
|
+
: -1
|
|
132
|
+
: direction,
|
|
133
|
+
]);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
if (orderByTuples.length > 0) {
|
|
137
|
+
query += `.sort(${this.logObject(orderByTuples)})`;
|
|
138
|
+
// @ts-expect-error ??
|
|
139
|
+
resultSet.sort(orderByTuples);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (limit !== undefined) {
|
|
143
|
+
query += `.limit(${limit})`;
|
|
144
|
+
resultSet.limit(limit);
|
|
145
|
+
}
|
|
146
|
+
if (offset !== undefined) {
|
|
147
|
+
query += `.skip(${offset})`;
|
|
148
|
+
resultSet.skip(offset);
|
|
149
|
+
}
|
|
150
|
+
const now = Date.now();
|
|
151
|
+
const res = await resultSet.toArray();
|
|
152
|
+
this.logQuery(`${query}.toArray();`, {
|
|
153
|
+
took: Date.now() - now,
|
|
154
|
+
results: res.length,
|
|
155
|
+
...loggerContext,
|
|
156
|
+
});
|
|
157
|
+
return res;
|
|
158
|
+
}
|
|
159
|
+
async insertOne(collection, data, ctx) {
|
|
160
|
+
return this.runQuery("insertOne", collection, data, undefined, ctx);
|
|
161
|
+
}
|
|
162
|
+
async insertMany(collection, data, ctx) {
|
|
163
|
+
return this.runQuery("insertMany", collection, data, undefined, ctx);
|
|
164
|
+
}
|
|
165
|
+
async updateMany(collection, where, data, ctx, upsert, upsertOptions) {
|
|
166
|
+
return this.runQuery("updateMany", collection, data, where, ctx, upsert, upsertOptions);
|
|
167
|
+
}
|
|
168
|
+
async bulkUpdateMany(collection, where, data, ctx, upsert, upsertOptions) {
|
|
169
|
+
return this.runQuery("bulkUpdateMany", collection, data, where, ctx, upsert, upsertOptions);
|
|
170
|
+
}
|
|
171
|
+
async deleteMany(collection, where, ctx) {
|
|
172
|
+
return this.runQuery("deleteMany", collection, undefined, where, ctx);
|
|
173
|
+
}
|
|
174
|
+
async aggregate(collection, pipeline, ctx, loggerContext) {
|
|
175
|
+
await this.ensureConnection();
|
|
176
|
+
collection = this.getCollectionName(collection);
|
|
177
|
+
/* istanbul ignore next */
|
|
178
|
+
const options = ctx ? { session: ctx } : {};
|
|
179
|
+
const query = `db.getCollection('${collection}').aggregate(${this.logObject(pipeline)}, ${this.logObject(options)}).toArray();`;
|
|
180
|
+
const now = Date.now();
|
|
181
|
+
const res = await this.getCollection(collection)
|
|
182
|
+
.aggregate(pipeline, options)
|
|
183
|
+
.toArray();
|
|
184
|
+
this.logQuery(query, {
|
|
185
|
+
took: Date.now() - now,
|
|
186
|
+
results: res.length,
|
|
187
|
+
...loggerContext,
|
|
188
|
+
});
|
|
189
|
+
return res;
|
|
190
|
+
}
|
|
191
|
+
async countDocuments(collection, where, ctx) {
|
|
192
|
+
return this.runQuery("countDocuments", collection, undefined, where, ctx);
|
|
193
|
+
}
|
|
194
|
+
async transactional(cb, options = {}) {
|
|
195
|
+
await this.ensureConnection();
|
|
196
|
+
const session = await this.begin(options);
|
|
197
|
+
try {
|
|
198
|
+
const ret = await cb(session);
|
|
199
|
+
await this.commit(session, options.eventBroadcaster);
|
|
200
|
+
return ret;
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
await this.rollback(session, options.eventBroadcaster);
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
await session.endSession();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
async begin(options = {}) {
|
|
211
|
+
await this.ensureConnection();
|
|
212
|
+
const { ctx, isolationLevel, eventBroadcaster, ...txOptions } = options;
|
|
213
|
+
if (!ctx) {
|
|
214
|
+
await eventBroadcaster?.dispatchEvent(core_1.EventType.beforeTransactionStart);
|
|
215
|
+
}
|
|
216
|
+
const session = ctx || this.client.startSession();
|
|
217
|
+
session.startTransaction(txOptions);
|
|
218
|
+
this.logQuery("db.begin();");
|
|
219
|
+
await eventBroadcaster?.dispatchEvent(core_1.EventType.afterTransactionStart, session);
|
|
220
|
+
return session;
|
|
221
|
+
}
|
|
222
|
+
async commit(ctx, eventBroadcaster) {
|
|
223
|
+
await this.ensureConnection();
|
|
224
|
+
await eventBroadcaster?.dispatchEvent(core_1.EventType.beforeTransactionCommit, ctx);
|
|
225
|
+
await ctx.commitTransaction();
|
|
226
|
+
this.logQuery("db.commit();");
|
|
227
|
+
await eventBroadcaster?.dispatchEvent(core_1.EventType.afterTransactionCommit, ctx);
|
|
228
|
+
}
|
|
229
|
+
async rollback(ctx, eventBroadcaster) {
|
|
230
|
+
await this.ensureConnection();
|
|
231
|
+
await eventBroadcaster?.dispatchEvent(core_1.EventType.beforeTransactionRollback, ctx);
|
|
232
|
+
await ctx.abortTransaction();
|
|
233
|
+
this.logQuery("db.rollback();");
|
|
234
|
+
await eventBroadcaster?.dispatchEvent(core_1.EventType.afterTransactionRollback, ctx);
|
|
235
|
+
}
|
|
236
|
+
async runQuery(method, collection, data, where, ctx, upsert, upsertOptions, loggerContext) {
|
|
237
|
+
await this.ensureConnection();
|
|
238
|
+
collection = this.getCollectionName(collection);
|
|
239
|
+
const logger = this.config.getLogger();
|
|
240
|
+
const options = ctx ? { session: ctx, upsert } : { upsert };
|
|
241
|
+
if (options.upsert === undefined) {
|
|
242
|
+
delete options.upsert;
|
|
243
|
+
}
|
|
244
|
+
const now = Date.now();
|
|
245
|
+
let res;
|
|
246
|
+
let query;
|
|
247
|
+
const log = (msg) => (logger.isEnabled("query") ? msg() : "");
|
|
248
|
+
switch (method) {
|
|
249
|
+
case "insertOne":
|
|
250
|
+
Object.keys(data)
|
|
251
|
+
.filter((k) => typeof data[k] === "undefined")
|
|
252
|
+
.forEach((k) => delete data[k]);
|
|
253
|
+
query = log(() => `db.getCollection('${collection}').insertOne(${this.logObject(data)}, ${this.logObject(options)});`);
|
|
254
|
+
res = await this.rethrow(this.getCollection(collection).insertOne(data, options), query);
|
|
255
|
+
break;
|
|
256
|
+
case "insertMany":
|
|
257
|
+
data.forEach((data) => Object.keys(data)
|
|
258
|
+
.filter((k) => typeof data[k] === "undefined")
|
|
259
|
+
.forEach((k) => delete data[k]));
|
|
260
|
+
query = log(() => `db.getCollection('${collection}').insertMany(${this.logObject(data)}, ${this.logObject(options)});`);
|
|
261
|
+
res = await this.rethrow(this.getCollection(collection).insertMany(data, options), query);
|
|
262
|
+
break;
|
|
263
|
+
case "updateMany": {
|
|
264
|
+
const payload = Object.keys(data).some((k) => k.startsWith("$"))
|
|
265
|
+
? data
|
|
266
|
+
: this.createUpdatePayload(data, upsertOptions);
|
|
267
|
+
query = log(() => `db.getCollection('${collection}').updateMany(${this.logObject(where)}, ${this.logObject(payload)}, ${this.logObject(options)});`);
|
|
268
|
+
res = (await this.rethrow(this.getCollection(collection).updateMany(where, payload, options), query));
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
case "bulkUpdateMany": {
|
|
272
|
+
query = log(() => `bulk = db.getCollection('${collection}').initializeUnorderedBulkOp(${this.logObject(options)});\n`);
|
|
273
|
+
const bulk = this.getCollection(collection).initializeUnorderedBulkOp(options);
|
|
274
|
+
data.forEach((row, idx) => {
|
|
275
|
+
const id = where[idx];
|
|
276
|
+
const cond = core_1.Utils.isPlainObject(id) ? id : { _id: id };
|
|
277
|
+
const doc = this.createUpdatePayload(row, upsertOptions);
|
|
278
|
+
if (upsert) {
|
|
279
|
+
query += log(() => `bulk.find(${this.logObject(cond)}).upsert().update(${this.logObject(doc)});\n`);
|
|
280
|
+
bulk.find(cond).upsert().update(doc);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
query += log(() => `bulk.find(${this.logObject(cond)}).update(${this.logObject(doc)});\n`);
|
|
284
|
+
bulk.find(cond).update(doc);
|
|
285
|
+
});
|
|
286
|
+
query += log(() => `bulk.execute()`);
|
|
287
|
+
res = await this.rethrow(bulk.execute(), query);
|
|
288
|
+
break;
|
|
289
|
+
}
|
|
290
|
+
case "deleteMany":
|
|
291
|
+
case "countDocuments":
|
|
292
|
+
query = log(() => `db.getCollection('${collection}').${method}(${this.logObject(where)}, ${this.logObject(options)});`);
|
|
293
|
+
res = await this.rethrow(this.getCollection(collection)[method](where, options), query);
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
this.logQuery(query, { took: Date.now() - now, ...loggerContext });
|
|
297
|
+
if (method === "countDocuments") {
|
|
298
|
+
return res;
|
|
299
|
+
}
|
|
300
|
+
return this.transformResult(res);
|
|
301
|
+
}
|
|
302
|
+
rethrow(promise, query) {
|
|
303
|
+
return promise.catch((e) => {
|
|
304
|
+
this.logQuery(query, { level: "error" });
|
|
305
|
+
e.message += "\nQuery: " + query;
|
|
306
|
+
throw e;
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
createUpdatePayload(row, upsertOptions) {
|
|
310
|
+
const doc = { $set: row };
|
|
311
|
+
const $unset = {};
|
|
312
|
+
core_1.Utils.keys(row)
|
|
313
|
+
.filter((k) => typeof row[k] === "undefined")
|
|
314
|
+
.forEach((k) => {
|
|
315
|
+
$unset[k] = "";
|
|
316
|
+
delete row[k];
|
|
317
|
+
});
|
|
318
|
+
if (upsertOptions) {
|
|
319
|
+
if (upsertOptions.onConflictAction === "ignore") {
|
|
320
|
+
doc.$setOnInsert = doc.$set;
|
|
321
|
+
delete doc.$set;
|
|
322
|
+
}
|
|
323
|
+
if (upsertOptions.onConflictMergeFields) {
|
|
324
|
+
doc.$setOnInsert = {};
|
|
325
|
+
upsertOptions.onConflictMergeFields.forEach((f) => {
|
|
326
|
+
doc.$setOnInsert[f] = doc.$set[f];
|
|
327
|
+
delete doc.$set[f];
|
|
328
|
+
});
|
|
329
|
+
const { $set, $setOnInsert } = doc;
|
|
330
|
+
doc.$set = $setOnInsert;
|
|
331
|
+
doc.$setOnInsert = $set;
|
|
332
|
+
}
|
|
333
|
+
else if (upsertOptions.onConflictExcludeFields) {
|
|
334
|
+
doc.$setOnInsert = {};
|
|
335
|
+
upsertOptions.onConflictExcludeFields.forEach((f) => {
|
|
336
|
+
doc.$setOnInsert[f] = doc.$set[f];
|
|
337
|
+
delete doc.$set[f];
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (core_1.Utils.hasObjectKeys($unset)) {
|
|
342
|
+
doc.$unset = $unset;
|
|
343
|
+
if (!core_1.Utils.hasObjectKeys(doc.$set)) {
|
|
344
|
+
delete doc.$set;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return doc;
|
|
348
|
+
}
|
|
349
|
+
transformResult(res) {
|
|
350
|
+
return {
|
|
351
|
+
affectedRows: res.modifiedCount || res.deletedCount || res.insertedCount || 0,
|
|
352
|
+
insertId: res.insertedId ?? res.insertedIds?.[0],
|
|
353
|
+
insertedIds: res.insertedIds ? Object.values(res.insertedIds) : undefined,
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
getCollectionName(name) {
|
|
357
|
+
name = core_1.Utils.className(name);
|
|
358
|
+
const meta = this.metadata.find(name);
|
|
359
|
+
return meta ? meta.collection : name;
|
|
360
|
+
}
|
|
361
|
+
logObject(o) {
|
|
362
|
+
if (o.session) {
|
|
363
|
+
o = { ...o, session: `[ClientSession]` };
|
|
364
|
+
}
|
|
365
|
+
return (0, util_1.inspect)(o, { depth: 5, compact: true, breakLength: 300 });
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
exports.MongoConnection = MongoConnection;
|
package/MongoDriver.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ClientSession } from "mongodb";
|
|
2
|
+
import { type Configuration, type CountOptions, DatabaseDriver, type EntityData, type EntityDictionary, type EntityField, EntityManagerType, type FilterQuery, type FindOneOptions, type FindOptions, type IDatabaseDriver, type NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type PopulateOptions, type QueryResult, type Transaction, type UpsertManyOptions, type UpsertOptions } from "@yandjin-mikro-orm/core";
|
|
3
|
+
import { MongoConnection } from "./MongoConnection";
|
|
4
|
+
import { MongoPlatform } from "./MongoPlatform";
|
|
5
|
+
import { MongoEntityManager } from "./MongoEntityManager";
|
|
6
|
+
export declare class MongoDriver extends DatabaseDriver<MongoConnection> {
|
|
7
|
+
[EntityManagerType]: MongoEntityManager<this>;
|
|
8
|
+
protected readonly connection: MongoConnection;
|
|
9
|
+
protected readonly platform: MongoPlatform;
|
|
10
|
+
constructor(config: Configuration);
|
|
11
|
+
createEntityManager<D extends IDatabaseDriver = IDatabaseDriver>(useContext?: boolean): D[typeof EntityManagerType];
|
|
12
|
+
find<T extends object, P extends string = never, F extends string = "*", E extends string = never>(entityName: string, where: FilterQuery<T>, options?: FindOptions<T, P, F, E>): Promise<EntityData<T>[]>;
|
|
13
|
+
findOne<T extends object, P extends string = never, F extends string = "*", E extends string = never>(entityName: string, where: FilterQuery<T>, options?: FindOneOptions<T, P, F, E>): Promise<EntityData<T> | null>;
|
|
14
|
+
findVirtual<T extends object>(entityName: string, where: FilterQuery<T>, options: FindOptions<T, any, any, any>): Promise<EntityData<T>[]>;
|
|
15
|
+
count<T extends object>(entityName: string, where: FilterQuery<T>, options?: CountOptions<T>, ctx?: Transaction<ClientSession>): Promise<number>;
|
|
16
|
+
nativeInsert<T extends object>(entityName: string, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
|
|
17
|
+
nativeInsertMany<T extends object>(entityName: string, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>>;
|
|
18
|
+
nativeUpdate<T extends object>(entityName: string, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T> & UpsertOptions<T>): Promise<QueryResult<T>>;
|
|
19
|
+
nativeUpdateMany<T extends object>(entityName: string, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateOptions<T> & UpsertManyOptions<T>): Promise<QueryResult<T>>;
|
|
20
|
+
nativeDelete<T extends object>(entityName: string, where: FilterQuery<T>, options?: {
|
|
21
|
+
ctx?: Transaction<ClientSession>;
|
|
22
|
+
}): Promise<QueryResult<T>>;
|
|
23
|
+
aggregate(entityName: string, pipeline: any[], ctx?: Transaction<ClientSession>): Promise<any[]>;
|
|
24
|
+
getPlatform(): MongoPlatform;
|
|
25
|
+
private renameFields;
|
|
26
|
+
private convertObjectIds;
|
|
27
|
+
private buildFilterById;
|
|
28
|
+
protected buildFields<T extends object, P extends string = never>(entityName: string, populate: PopulateOptions<T>[], fields?: readonly EntityField<T, P>[], exclude?: string[]): string[] | undefined;
|
|
29
|
+
}
|