diff --git a/packages/core/src/MikroORM.ts b/packages/core/src/MikroORM.ts index 09384842ac70..801c8a5d5446 100644 --- a/packages/core/src/MikroORM.ts +++ b/packages/core/src/MikroORM.ts @@ -22,7 +22,7 @@ export class MikroORM { * Initialize the ORM, load entity metadata, create EntityManager and connect to the database. * If you omit the `options` parameter, your CLI config will be used. */ - static async init(options?: Options | Configuration): Promise> { + static async init(options?: Options | Configuration, connect = true): Promise> { if (!options) { options = await ConfigurationLoader.getConfiguration(); } @@ -34,10 +34,13 @@ export class MikroORM { orm.em = orm.driver.createEntityManager(); orm.metadata.decorate(orm.em); orm.driver.setMetadata(orm.metadata); - await orm.connect(); - if (orm.config.get('ensureIndexes')) { - await orm.driver.ensureIndexes(); + if (connect) { + await orm.connect(); + + if (orm.config.get('ensureIndexes')) { + await orm.driver.ensureIndexes(); + } } return orm; diff --git a/packages/mongodb/src/MongoConnection.ts b/packages/mongodb/src/MongoConnection.ts index 82e035b2e318..10575bdabc38 100644 --- a/packages/mongodb/src/MongoConnection.ts +++ b/packages/mongodb/src/MongoConnection.ts @@ -20,7 +20,8 @@ export class MongoConnection extends Connection { } async isConnected(): Promise { - return this.client.isConnected(); + const ret = this.client?.isConnected(); + return !!ret; } getCollection(name: EntityName): Collection { diff --git a/tests/MikroORM.test.ts b/tests/MikroORM.test.ts index 8d55c8f8744e..2f75a239a507 100644 --- a/tests/MikroORM.test.ts +++ b/tests/MikroORM.test.ts @@ -91,11 +91,14 @@ describe('MikroORM', () => { const pkg = { 'mikro-orm': { useTsNode: true } } as any; jest.mock('../package.json', () => pkg, { virtual: true }); - const orm = await MikroORM.init(); + const orm = await MikroORM.init(undefined, false); expect(orm).toBeInstanceOf(MikroORM); expect(orm.em).toBeInstanceOf(EntityManager); expect(Object.keys(orm.getMetadata().getAll()).sort()).toEqual(['Test']); + expect(await orm.isConnected()).toBe(false); + + await orm.connect(); expect(await orm.isConnected()).toBe(true); await orm.close();