Skip to content

Commit

Permalink
feat(mongo): allow reusing mongo client via driverOptions
Browse files Browse the repository at this point in the history
Closes #3352
  • Loading branch information
B4nan committed Jul 31, 2022
1 parent 6c589b0 commit df59ebf
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/mongodb/src/MongoConnection.ts
Expand Up @@ -30,9 +30,16 @@ export class MongoConnection extends Connection {
}

async connect(): Promise<void> {
this.client = new MongoClient(this.config.getClientUrl(), this.getConnectionOptions());
const driverOptions = this.config.get('driverOptions');

if (driverOptions instanceof MongoClient) {
this.logger.log('info', 'Reusing MongoClient provided via `driverOptions`');
this.client = driverOptions;
} else {
this.client = new MongoClient(this.config.getClientUrl(), this.getConnectionOptions());
await this.client.connect();
}

await this.client.connect();
this.db = this.client.db(this.config.get('dbName'));
this.connected = true;
}
Expand All @@ -46,6 +53,10 @@ export class MongoConnection extends Connection {
return this.connected;
}

getClient(): MongoClient {
return this.client;
}

getCollection<T>(name: EntityName<T>): Collection<T> {
return this.db.collection<T>(this.getCollectionName(name));
}
Expand Down
24 changes: 24 additions & 0 deletions tests/features/reusing-mongo-client.test.ts
@@ -0,0 +1,24 @@
import { MikroORM } from '@mikro-orm/core';
import { MongoDriver } from '@mikro-orm/mongodb';
import { Author, schema } from '../entities';

test('should allow reusing mongo connection', async () => {
const orm = await MikroORM.init({
driver: MongoDriver,
dbName: 'mikro_orm_test',
entities: [Author, schema],
});
const mongo = orm.em.getConnection().getClient();

const orm2 = await MikroORM.init({
driver: MongoDriver,
dbName: 'mikro_orm_test',
entities: [Author, schema],
driverOptions: mongo,
});

await expect(orm.em.find(Author, {})).resolves.toHaveLength(0);
await orm2.close(); // closing orm2 will make orm1 disconnect too as they share mongo client
await expect(orm.isConnected()).resolves.toBe(true);
await expect(orm.em.find(Author, {})).rejects.toThrow('Client must be connected before running operations');
});

0 comments on commit df59ebf

Please sign in to comment.