@mikro-orm/mongodb 7.0.0-dev.23 → 7.0.0-dev.231

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.
@@ -1,10 +1,12 @@
1
- import { MongoClient, type ClientSession, type Collection, type Db, type MongoClientOptions, type TransactionOptions } from 'mongodb';
2
- import { Connection, type AnyEntity, type Configuration, 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 '@mikro-orm/core';
1
+ import { type ClientSession, type Collection, type Db, MongoClient, type MongoClientOptions, type TransactionOptions } from 'mongodb';
2
+ import { type AnyEntity, type Configuration, Connection, type ConnectionOptions, type ConnectionType, type EntityData, type EntityName, type FilterQuery, type IsolationLevel, type LoggingOptions, type QueryOrderMap, type QueryResult, type Transaction, type TransactionEventBroadcaster, type UpsertManyOptions, type UpsertOptions } from '@mikro-orm/core';
3
3
  export declare class MongoConnection extends Connection {
4
- protected client: MongoClient;
5
- protected db: Db;
4
+ #private;
6
5
  constructor(config: Configuration, options?: ConnectionOptions, type?: ConnectionType);
7
- connect(): Promise<void>;
6
+ connect(options?: {
7
+ skipOnConnect?: boolean;
8
+ }): Promise<void>;
9
+ createClient(): void;
8
10
  close(force?: boolean): Promise<void>;
9
11
  isConnected(): Promise<boolean>;
10
12
  checkConnection(): Promise<{
@@ -20,17 +22,19 @@ export declare class MongoConnection extends Connection {
20
22
  listCollections(): Promise<string[]>;
21
23
  dropCollection(name: EntityName<AnyEntity>): Promise<boolean>;
22
24
  mapOptions(overrides: MongoClientOptions): MongoClientOptions;
23
- getClientUrl(): string;
24
25
  getDb(): Db;
25
26
  execute(query: string): Promise<any>;
26
- 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>[]>;
27
- insertOne<T extends object>(collection: string, data: Partial<T>, ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
28
- insertMany<T extends object>(collection: string, data: Partial<T>[], ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
29
- updateMany<T extends object>(collection: string, where: FilterQuery<T>, data: Partial<T>, ctx?: Transaction<ClientSession>, upsert?: boolean, upsertOptions?: UpsertOptions<T>): Promise<QueryResult<T>>;
30
- bulkUpdateMany<T extends object>(collection: string, where: FilterQuery<T>[], data: Partial<T>[], ctx?: Transaction<ClientSession>, upsert?: boolean, upsertOptions?: UpsertManyOptions<T>): Promise<QueryResult<T>>;
31
- deleteMany<T extends object>(collection: string, where: FilterQuery<T>, ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
32
- aggregate<T extends object = any>(collection: string, pipeline: any[], ctx?: Transaction<ClientSession>, loggerContext?: LoggingOptions): Promise<T[]>;
33
- countDocuments<T extends object>(collection: string, where: FilterQuery<T>, ctx?: Transaction<ClientSession>): Promise<number>;
27
+ find<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, orderBy?: QueryOrderMap<T> | QueryOrderMap<T>[], limit?: number, offset?: number, fields?: string[], ctx?: Transaction<ClientSession>, loggerContext?: LoggingOptions): Promise<EntityData<T>[]>;
28
+ stream<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, orderBy?: QueryOrderMap<T> | QueryOrderMap<T>[], limit?: number, offset?: number, fields?: string[], ctx?: Transaction<ClientSession>, loggerContext?: LoggingOptions): AsyncIterableIterator<T>;
29
+ private _find;
30
+ insertOne<T extends object>(entityName: EntityName<T>, data: Partial<T>, ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
31
+ insertMany<T extends object>(entityName: EntityName<T>, data: Partial<T>[], ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
32
+ updateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, data: Partial<T>, ctx?: Transaction<ClientSession>, upsert?: boolean, upsertOptions?: UpsertOptions<T>): Promise<QueryResult<T>>;
33
+ bulkUpdateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>[], data: Partial<T>[], ctx?: Transaction<ClientSession>, upsert?: boolean, upsertOptions?: UpsertManyOptions<T>): Promise<QueryResult<T>>;
34
+ deleteMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, ctx?: Transaction<ClientSession>): Promise<QueryResult<T>>;
35
+ aggregate<T extends object = any>(entityName: EntityName<T>, pipeline: any[], ctx?: Transaction<ClientSession>, loggerContext?: LoggingOptions): Promise<T[]>;
36
+ streamAggregate<T extends object>(entityName: EntityName<T>, pipeline: any[], ctx?: Transaction<ClientSession>, loggerContext?: LoggingOptions, stream?: boolean): AsyncIterableIterator<T>;
37
+ countDocuments<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, ctx?: Transaction<ClientSession>): Promise<number>;
34
38
  transactional<T>(cb: (trx: Transaction<ClientSession>) => Promise<T>, options?: {
35
39
  isolationLevel?: IsolationLevel;
36
40
  ctx?: Transaction<ClientSession>;
@@ -1,49 +1,54 @@
1
- import { ObjectId, MongoClient, } from 'mongodb';
2
- import { inspect } from 'node:util';
3
- import { Connection, EventType, QueryOrder, Utils, ValidationError, } from '@mikro-orm/core';
1
+ import { MongoClient, ObjectId, } from 'mongodb';
2
+ import { Connection, EventType, inspect, QueryOrder, Utils, ValidationError, } from '@mikro-orm/core';
4
3
  export class MongoConnection extends Connection {
5
- client;
6
- db;
4
+ #client;
5
+ #db;
7
6
  constructor(config, options, type = 'write') {
8
7
  super(config, options, type);
9
8
  // @ts-ignore
10
- ObjectId.prototype[inspect.custom] = function () {
9
+ ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
11
10
  return `ObjectId('${this.toHexString()}')`;
12
11
  };
13
12
  // @ts-ignore
14
- Date.prototype[inspect.custom] = function () {
13
+ Date.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
15
14
  return `ISODate('${this.toISOString()}')`;
16
15
  };
17
16
  }
18
- async connect() {
17
+ async connect(options) {
18
+ this.getClient();
19
+ this.connected = true;
20
+ if (options?.skipOnConnect !== true) {
21
+ await this.onConnect();
22
+ }
23
+ }
24
+ createClient() {
19
25
  let driverOptions = this.options.driverOptions ?? this.config.get('driverOptions');
20
26
  if (typeof driverOptions === 'function') {
21
- driverOptions = await driverOptions();
27
+ driverOptions = driverOptions();
22
28
  }
23
29
  if (driverOptions instanceof MongoClient) {
24
30
  this.logger.log('info', 'Reusing MongoClient provided via `driverOptions`');
25
- this.client = driverOptions;
31
+ this.#client = driverOptions;
26
32
  }
27
33
  else {
28
- this.client = new MongoClient(this.config.getClientUrl(), this.mapOptions(driverOptions));
29
- await this.client.connect();
34
+ this.#client = new MongoClient(this.config.get('clientUrl'), this.mapOptions(driverOptions));
30
35
  const onCreateConnection = this.options.onCreateConnection ?? this.config.get('onCreateConnection');
31
- /* v8 ignore next 3 */
32
- this.client.on('connectionCreated', () => {
33
- void onCreateConnection?.(this.client);
36
+ /* v8 ignore next */
37
+ this.#client.on('connectionCreated', () => {
38
+ void onCreateConnection?.(this.#client);
34
39
  });
35
40
  }
36
- this.db = this.client.db(this.config.get('dbName'));
37
- this.connected = true;
41
+ this.#db = this.#client.db(this.config.get('dbName'));
38
42
  }
39
43
  async close(force) {
40
- await this.client?.close(!!force);
44
+ await this.#client?.close(force);
41
45
  this.connected = false;
46
+ this.#client = undefined;
42
47
  }
43
48
  async isConnected() {
44
49
  try {
45
- const res = await this.db?.command({ ping: 1 });
46
- return this.connected = !!res.ok;
50
+ const res = await this.#db?.command({ ping: 1 });
51
+ return this.connected = !!res?.ok;
47
52
  }
48
53
  catch (error) {
49
54
  return this.connected = false;
@@ -51,8 +56,8 @@ export class MongoConnection extends Connection {
51
56
  }
52
57
  async checkConnection() {
53
58
  try {
54
- const res = await this.db?.command({ ping: 1 });
55
- return res.ok
59
+ const res = await this.#db?.command({ ping: 1 });
60
+ return res?.ok
56
61
  ? { ok: true }
57
62
  : { ok: false, reason: 'Ping reply does not feature "ok" property, or it evaluates to "false"' };
58
63
  }
@@ -61,20 +66,23 @@ export class MongoConnection extends Connection {
61
66
  }
62
67
  }
63
68
  getClient() {
64
- return this.client;
69
+ if (!this.#client) {
70
+ this.createClient();
71
+ }
72
+ return this.#client;
65
73
  }
66
74
  getCollection(name) {
67
- return this.db.collection(this.getCollectionName(name));
75
+ return this.getDb().collection(this.getCollectionName(name));
68
76
  }
69
77
  async createCollection(name) {
70
- return this.db.createCollection(this.getCollectionName(name));
78
+ return this.getDb().createCollection(this.getCollectionName(name));
71
79
  }
72
80
  async listCollections() {
73
- const collections = await this.db.listCollections({}, { nameOnly: true }).toArray();
81
+ const collections = await this.getDb().listCollections({}, { nameOnly: true }).toArray();
74
82
  return collections.map(c => c.name);
75
83
  }
76
84
  async dropCollection(name) {
77
- return this.db.dropCollection(this.getCollectionName(name));
85
+ return this.getDb().dropCollection(this.getCollectionName(name));
78
86
  }
79
87
  mapOptions(overrides) {
80
88
  const ret = {};
@@ -96,26 +104,33 @@ export class MongoConnection extends Connection {
96
104
  };
97
105
  return Utils.mergeConfig(ret, overrides);
98
106
  }
99
- getClientUrl() {
100
- const options = this.mapOptions(this.options.driverOptions ?? {});
101
- const clientUrl = this.config.getClientUrl(true);
102
- const match = clientUrl.match(/^(\w+):\/\/((.*@.+)|.+)$/);
103
- return match ? `${match[1]}://${options.auth ? options.auth.username + ':*****@' : ''}${match[2]}` : clientUrl;
104
- }
105
107
  getDb() {
106
- return this.db;
108
+ this.#db ??= this.getClient().db(this.config.get('dbName'));
109
+ return this.#db;
107
110
  }
108
111
  async execute(query) {
109
112
  throw new Error(`${this.constructor.name} does not support generic execute method`);
110
113
  }
111
- async find(collection, where, orderBy, limit, offset, fields, ctx, loggerContext) {
114
+ async find(entityName, where, orderBy, limit, offset, fields, ctx, loggerContext) {
115
+ const { cursor, query } = await this._find(entityName, where, orderBy, limit, offset, fields, ctx, loggerContext);
116
+ const now = Date.now();
117
+ const res = await cursor.toArray();
118
+ this.logQuery(`${query}.toArray();`, { took: Date.now() - now, results: res.length, ...loggerContext });
119
+ return res;
120
+ }
121
+ async *stream(entityName, where, orderBy, limit, offset, fields, ctx, loggerContext) {
122
+ const { cursor, query } = await this._find(entityName, where, orderBy, limit, offset, fields, ctx, loggerContext);
123
+ this.logQuery(`${query}.toArray();`, loggerContext);
124
+ yield* cursor;
125
+ }
126
+ async _find(entityName, where, orderBy, limit, offset, fields, ctx, loggerContext) {
112
127
  await this.ensureConnection();
113
- collection = this.getCollectionName(collection);
128
+ const collection = this.getCollectionName(entityName);
114
129
  const options = ctx ? { session: ctx } : {};
115
130
  if (fields) {
116
131
  options.projection = fields.reduce((o, k) => Object.assign(o, { [k]: 1 }), {});
117
132
  }
118
- const resultSet = this.getCollection(collection).find(where, options);
133
+ const resultSet = this.getCollection(entityName).find(where, options);
119
134
  let query = `db.getCollection('${collection}').find(${this.logObject(where)}, ${this.logObject(options)})`;
120
135
  orderBy = Utils.asArray(orderBy);
121
136
  if (Array.isArray(orderBy) && orderBy.length > 0) {
@@ -123,12 +138,11 @@ export class MongoConnection extends Connection {
123
138
  orderBy.forEach(o => {
124
139
  Utils.keys(o).forEach(k => {
125
140
  const direction = o[k];
126
- orderByTuples.push([k.toString(), Utils.isString(direction) ? direction.toUpperCase() === QueryOrder.ASC ? 1 : -1 : direction]);
141
+ orderByTuples.push([k.toString(), typeof direction === 'string' ? direction.toUpperCase() === QueryOrder.ASC ? 1 : -1 : direction]);
127
142
  });
128
143
  });
129
144
  if (orderByTuples.length > 0) {
130
145
  query += `.sort(${this.logObject(orderByTuples)})`;
131
- // @ts-expect-error ??
132
146
  resultSet.sort(orderByTuples);
133
147
  }
134
148
  }
@@ -140,39 +154,46 @@ export class MongoConnection extends Connection {
140
154
  query += `.skip(${offset})`;
141
155
  resultSet.skip(offset);
142
156
  }
143
- const now = Date.now();
144
- const res = await resultSet.toArray();
145
- this.logQuery(`${query}.toArray();`, { took: Date.now() - now, results: res.length, ...loggerContext });
146
- return res;
157
+ return { cursor: resultSet, query };
147
158
  }
148
- async insertOne(collection, data, ctx) {
149
- return this.runQuery('insertOne', collection, data, undefined, ctx);
159
+ async insertOne(entityName, data, ctx) {
160
+ return this.runQuery('insertOne', entityName, data, undefined, ctx);
150
161
  }
151
- async insertMany(collection, data, ctx) {
152
- return this.runQuery('insertMany', collection, data, undefined, ctx);
162
+ async insertMany(entityName, data, ctx) {
163
+ return this.runQuery('insertMany', entityName, data, undefined, ctx);
153
164
  }
154
- async updateMany(collection, where, data, ctx, upsert, upsertOptions) {
155
- return this.runQuery('updateMany', collection, data, where, ctx, upsert, upsertOptions);
165
+ async updateMany(entityName, where, data, ctx, upsert, upsertOptions) {
166
+ return this.runQuery('updateMany', entityName, data, where, ctx, upsert, upsertOptions);
156
167
  }
157
- async bulkUpdateMany(collection, where, data, ctx, upsert, upsertOptions) {
158
- return this.runQuery('bulkUpdateMany', collection, data, where, ctx, upsert, upsertOptions);
168
+ async bulkUpdateMany(entityName, where, data, ctx, upsert, upsertOptions) {
169
+ return this.runQuery('bulkUpdateMany', entityName, data, where, ctx, upsert, upsertOptions);
159
170
  }
160
- async deleteMany(collection, where, ctx) {
161
- return this.runQuery('deleteMany', collection, undefined, where, ctx);
171
+ async deleteMany(entityName, where, ctx) {
172
+ return this.runQuery('deleteMany', entityName, undefined, where, ctx);
162
173
  }
163
- async aggregate(collection, pipeline, ctx, loggerContext) {
174
+ async aggregate(entityName, pipeline, ctx, loggerContext) {
164
175
  await this.ensureConnection();
165
- collection = this.getCollectionName(collection);
176
+ const collection = this.getCollectionName(entityName);
166
177
  /* v8 ignore next */
167
178
  const options = ctx ? { session: ctx } : {};
168
179
  const query = `db.getCollection('${collection}').aggregate(${this.logObject(pipeline)}, ${this.logObject(options)}).toArray();`;
169
180
  const now = Date.now();
170
- const res = await this.getCollection(collection).aggregate(pipeline, options).toArray();
181
+ const res = await this.getCollection(entityName).aggregate(pipeline, options).toArray();
171
182
  this.logQuery(query, { took: Date.now() - now, results: res.length, ...loggerContext });
172
183
  return res;
173
184
  }
174
- async countDocuments(collection, where, ctx) {
175
- return this.runQuery('countDocuments', collection, undefined, where, ctx);
185
+ async *streamAggregate(entityName, pipeline, ctx, loggerContext, stream = false) {
186
+ await this.ensureConnection();
187
+ const collection = this.getCollectionName(entityName);
188
+ /* v8 ignore next */
189
+ const options = ctx ? { session: ctx } : {};
190
+ const query = `db.getCollection('${collection}').aggregate(${this.logObject(pipeline)}, ${this.logObject(options)})};`;
191
+ const cursor = this.getCollection(entityName).aggregate(pipeline, options);
192
+ this.logQuery(query, { ...loggerContext });
193
+ yield* cursor;
194
+ }
195
+ async countDocuments(entityName, where, ctx) {
196
+ return this.runQuery('countDocuments', entityName, undefined, where, ctx);
176
197
  }
177
198
  async transactional(cb, options = {}) {
178
199
  await this.ensureConnection();
@@ -196,7 +217,7 @@ export class MongoConnection extends Connection {
196
217
  if (!ctx) {
197
218
  await eventBroadcaster?.dispatchEvent(EventType.beforeTransactionStart);
198
219
  }
199
- const session = ctx || this.client.startSession();
220
+ const session = ctx || this.getClient().startSession();
200
221
  session.startTransaction(txOptions);
201
222
  this.logQuery('db.begin();');
202
223
  await eventBroadcaster?.dispatchEvent(EventType.afterTransactionStart, session);
@@ -216,9 +237,9 @@ export class MongoConnection extends Connection {
216
237
  this.logQuery('db.rollback();');
217
238
  await eventBroadcaster?.dispatchEvent(EventType.afterTransactionRollback, ctx);
218
239
  }
219
- async runQuery(method, collection, data, where, ctx, upsert, upsertOptions, loggerContext) {
240
+ async runQuery(method, entityName, data, where, ctx, upsert, upsertOptions, loggerContext) {
220
241
  await this.ensureConnection();
221
- collection = this.getCollectionName(collection);
242
+ const collection = this.getCollectionName(entityName);
222
243
  const logger = this.config.getLogger();
223
244
  const options = ctx ? { session: ctx, upsert } : { upsert };
224
245
  if (options.upsert === undefined) {
@@ -232,22 +253,22 @@ export class MongoConnection extends Connection {
232
253
  case 'insertOne':
233
254
  Object.keys(data).filter(k => typeof data[k] === 'undefined').forEach(k => delete data[k]);
234
255
  query = log(() => `db.getCollection('${collection}').insertOne(${this.logObject(data)}, ${this.logObject(options)});`);
235
- res = await this.rethrow(this.getCollection(collection).insertOne(data, options), query);
256
+ res = await this.rethrow(this.getCollection(entityName).insertOne(data, options), query);
236
257
  break;
237
258
  case 'insertMany':
238
259
  data.forEach(data => Object.keys(data).filter(k => typeof data[k] === 'undefined').forEach(k => delete data[k]));
239
260
  query = log(() => `db.getCollection('${collection}').insertMany(${this.logObject(data)}, ${this.logObject(options)});`);
240
- res = await this.rethrow(this.getCollection(collection).insertMany(data, options), query);
261
+ res = await this.rethrow(this.getCollection(entityName).insertMany(data, options), query);
241
262
  break;
242
263
  case 'updateMany': {
243
- const payload = Object.keys(data).some(k => k.startsWith('$')) ? data : this.createUpdatePayload(data, upsertOptions);
264
+ const payload = Object.keys(data).every(k => k.startsWith('$')) ? data : this.createUpdatePayload(data, upsertOptions);
244
265
  query = log(() => `db.getCollection('${collection}').updateMany(${this.logObject(where)}, ${this.logObject(payload)}, ${this.logObject(options)});`);
245
- res = await this.rethrow(this.getCollection(collection).updateMany(where, payload, options), query);
266
+ res = await this.rethrow(this.getCollection(entityName).updateMany(where, payload, options), query);
246
267
  break;
247
268
  }
248
269
  case 'bulkUpdateMany': {
249
270
  query = log(() => `bulk = db.getCollection('${collection}').initializeUnorderedBulkOp(${this.logObject(options)});\n`);
250
- const bulk = this.getCollection(collection).initializeUnorderedBulkOp(options);
271
+ const bulk = this.getCollection(entityName).initializeUnorderedBulkOp(options);
251
272
  data.forEach((row, idx) => {
252
273
  const id = where[idx];
253
274
  const cond = Utils.isPlainObject(id) ? id : { _id: id };
@@ -273,7 +294,7 @@ export class MongoConnection extends Connection {
273
294
  case 'deleteMany':
274
295
  case 'countDocuments':
275
296
  query = log(() => `db.getCollection('${collection}').${method}(${this.logObject(where)}, ${this.logObject(options)});`);
276
- res = await this.rethrow(this.getCollection(collection)[method](where, options), query);
297
+ res = await this.rethrow(this.getCollection(entityName)[method](where, options), query);
277
298
  break;
278
299
  }
279
300
  this.logQuery(query, { took: Date.now() - now, ...loggerContext });
@@ -290,14 +311,28 @@ export class MongoConnection extends Connection {
290
311
  });
291
312
  }
292
313
  createUpdatePayload(row, upsertOptions) {
314
+ row = { ...row };
293
315
  const doc = { $set: row };
294
- const $unset = {};
295
- Utils.keys(row)
296
- .filter(k => typeof row[k] === 'undefined')
297
- .forEach(k => {
298
- $unset[k] = '';
299
- delete row[k];
316
+ Utils.keys(row).forEach(k => {
317
+ if (k.toString().startsWith('$')) {
318
+ doc[k] = row[k];
319
+ delete row[k];
320
+ }
300
321
  });
322
+ const $unset = {};
323
+ const $inc = {};
324
+ for (const k of Utils.keys(row)) {
325
+ const item = row[k];
326
+ if (typeof item === 'undefined') {
327
+ $unset[k] = '';
328
+ delete row[k];
329
+ continue;
330
+ }
331
+ if (Utils.isPlainObject(item) && '$inc' in item) {
332
+ $inc[k] = item.$inc;
333
+ delete row[k];
334
+ }
335
+ }
301
336
  if (upsertOptions) {
302
337
  if (upsertOptions.onConflictAction === 'ignore') {
303
338
  doc.$setOnInsert = doc.$set;
@@ -323,9 +358,12 @@ export class MongoConnection extends Connection {
323
358
  }
324
359
  if (Utils.hasObjectKeys($unset)) {
325
360
  doc.$unset = $unset;
326
- if (!Utils.hasObjectKeys(doc.$set)) {
327
- delete doc.$set;
328
- }
361
+ }
362
+ if (Utils.hasObjectKeys($inc)) {
363
+ doc.$inc = $inc;
364
+ }
365
+ if (!Utils.hasObjectKeys(doc.$set)) {
366
+ delete doc.$set;
329
367
  }
330
368
  return doc;
331
369
  }
@@ -336,13 +374,12 @@ export class MongoConnection extends Connection {
336
374
  insertedIds: res.insertedIds ? Object.values(res.insertedIds) : undefined,
337
375
  };
338
376
  }
339
- getCollectionName(name) {
340
- name = Utils.className(name);
341
- const meta = this.metadata.find(name);
342
- return meta ? meta.collection : name;
377
+ getCollectionName(entityName) {
378
+ const meta = this.metadata.find(entityName);
379
+ return meta ? meta.collection : Utils.className(entityName);
343
380
  }
344
381
  logObject(o) {
345
- if (o.session) {
382
+ if (o?.session) {
346
383
  o = { ...o, session: `[ClientSession]` };
347
384
  }
348
385
  return inspect(o, { depth: 5, compact: true, breakLength: 300 });
package/MongoDriver.d.ts CHANGED
@@ -1,29 +1,38 @@
1
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 NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type PopulateOptions, type PopulatePath, type QueryResult, type Transaction, type UpsertManyOptions, type UpsertOptions } from '@mikro-orm/core';
2
+ import { type Configuration, type Constructor, type CountOptions, DatabaseDriver, type EntityData, type EntityDictionary, type EntityField, EntityManagerType, type EntityName, type FilterQuery, type FindOneOptions, type FindOptions, type NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type PopulateOptions, type PopulatePath, type QueryResult, type StreamOptions, type Transaction, type UpsertManyOptions, type UpsertOptions } from '@mikro-orm/core';
3
3
  import { MongoConnection } from './MongoConnection.js';
4
4
  import { MongoPlatform } from './MongoPlatform.js';
5
5
  import { MongoEntityManager } from './MongoEntityManager.js';
6
+ import { MongoMikroORM } from './MongoMikroORM.js';
6
7
  export declare class MongoDriver extends DatabaseDriver<MongoConnection> {
7
8
  [EntityManagerType]: MongoEntityManager<this>;
8
9
  protected readonly connection: MongoConnection;
9
10
  protected readonly platform: MongoPlatform;
10
11
  constructor(config: Configuration);
11
12
  createEntityManager(useContext?: boolean): this[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 = PopulatePath.ALL, 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?: {
13
+ stream<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options: StreamOptions<T, any, any, any> & {
14
+ rawResults?: boolean;
15
+ }): AsyncIterableIterator<T>;
16
+ find<T extends object, P extends string = never, F extends string = '*', E extends string = never>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOptions<T, P, F, E>): Promise<EntityData<T>[]>;
17
+ findOne<T extends object, P extends string = never, F extends string = PopulatePath.ALL, E extends string = never>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOneOptions<T, P, F, E>): Promise<EntityData<T> | null>;
18
+ findVirtual<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options: FindOptions<T, any, any, any>): Promise<EntityData<T>[]>;
19
+ streamVirtual<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options: FindOptions<T, any, any, any>): AsyncIterableIterator<EntityData<T>>;
20
+ count<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options?: CountOptions<T>, ctx?: Transaction<ClientSession>): Promise<number>;
21
+ nativeInsert<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T>): Promise<QueryResult<T>>;
22
+ nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>): Promise<QueryResult<T>>;
23
+ nativeUpdate<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T> & UpsertOptions<T>): Promise<QueryResult<T>>;
24
+ nativeUpdateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateOptions<T> & UpsertManyOptions<T>): Promise<QueryResult<T>>;
25
+ nativeDelete<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, options?: {
21
26
  ctx?: Transaction<ClientSession>;
22
27
  }): Promise<QueryResult<T>>;
23
- aggregate(entityName: string, pipeline: any[], ctx?: Transaction<ClientSession>): Promise<any[]>;
28
+ aggregate(entityName: EntityName, pipeline: any[], ctx?: Transaction<ClientSession>): Promise<any[]>;
29
+ streamAggregate<T extends object>(entityName: EntityName<T>, pipeline: any[], ctx?: Transaction<ClientSession>): AsyncIterableIterator<T>;
24
30
  getPlatform(): MongoPlatform;
25
31
  private renameFields;
26
32
  private convertObjectIds;
27
33
  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;
34
+ protected buildFields<T extends object, P extends string = never>(entityName: EntityName<T>, populate: PopulateOptions<T>[], fields?: readonly EntityField<T, P>[], exclude?: string[]): string[] | undefined;
35
+ private handleVersionProperty;
36
+ /** @inheritDoc */
37
+ getORMClass(): Constructor<MongoMikroORM>;
29
38
  }