MikroORM is a Typescript ORM for NodeJS. Using MikroORM, we can connect our NodeJS applications to the database of choice. It also supports most of the major databases such as PostgreSQL, MySQL, MongoDB. In order to configure a database connection, we need to use the Mikro ORM Init function.

The Mikro ORM Init function is used to bootstrap the application’s database connection. Basically, the init function takes in a bunch of options and configures the connection accordingly. While the application sounds simple, there are a few considerations to make when using the MikroORM.init() function.

In this post, we will cover the various aspects of using the Mikro ORM Init Function.

1 – Installation of MikroORM Packages

To get started with MikroORM with a NodeJS application, we need to first install the @mikro-orm/core package and the database driver package.

We can install the necessary packages using the below command:

npm i -s @mikro-orm/core @mikro-orm/mysql

In this case, we are going with MySQL as the database. In case you want to use another database, you need to install the appropriate driver package for that particular database. The @mikro-orm/core package is common for all databases.

Since we are working with Typescript, we need to also install a few packages to support the same.

$ npm i -s typescript ts-node @types/node

Also, as we want to use MikroORM decorators, we also need to enable decorator support for our Typescript code. To do so, we need to add the below configuration properties to the tsconfig.json file.

"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,

2 – First look at Mikro ORM Init Function

Once we install the necessary packages, we can bootstrap our application using the MikroORM.init() function.

See below example:

import { MikroORM } from '@mikro-orm/core';
import type { MySqlDriver } from '@mikro-orm/mysql';

const orm = await MikroORM.init<MySqlDriver>({
  entities: ['./dist/entities'], // path to our JS entities (dist), relative to `baseDir`
  entitiesTs: ['./src/entities'], // path to our TS entities (src), relative to `baseDir`
  dbName: 'testdb2',
  type: 'mysql',
});

The Mikro ORM Init function takes a few parameters as input. Basically, these are configuration options.

  • entities option specifies the path to the JS entities (after compilation).
  • entitiesTs points to the path where the typescript source entity files are present.
  • dbName is the name of the database.
  • type is the database provider. In our case, it is mysql.

There are a bunch of other configuration options as well. However, these are the bare minimum. We will look at other advanced options in future posts

Important point to note here is MikroORM’s Entity Discovery mechanism. The entities and entitiesTs values specify the path to our entity files. These fields can accept an array of file paths. Also, we can use wildcards to specify more complex file paths if needed.

3 – Mikro-orm Config File with Init Function

While we can pass configuration options in the MikroORM.init() call, it is much better to maintain the configuration options in a separate file. Also, it is advantageous to use the MikroORM schema generator to generate our database and tables.

In order to support these options, we need to install the MikroORM CLI or Command Line Interface package.

$ npm install --save-dev @mikro-orm/cli

Now, we can create a separate Mikro-orm config file in the src directory of our project. See below:

import { Options } from "@mikro-orm/core";
import { Test } from "./entities/test-entity";

const options: Options = {
    entities: [Test],
    type: 'mysql',
    dbName: 'testdb2',
    debug: true,
    port: 3306,
    user: 'root',
    password: 'password',
}

export default options;

Basically, these are the same properties we specify in the MikroORM init function. Additionally, we also added properties such as port and database credentials.

Another important thing to note here is the entities array. Here, we specify the entity types directly rather than the folder path to our entity files. In this case, there is no need for the entitiesTs field.

For MikroORM to detect this particular config file file, we also need to add some settings to the package.json file. See below:

"mikro-orm": {
    "useTsNode": true,
    "configPaths": [
      "./src/mikro-orm.config.ts",
      "./dist/mikro-orm.config.js"
    ]
  }

Below is the code for the Test entity file.

import { Entity, PrimaryKey, Property } from "@mikro-orm/core";

@Entity()
export class Test {
    
    @PrimaryKey()
    _id!: number;

    @Property()
    name: string;

    constructor(name: string) {
        this.name = name;
    }
}

This is a very simple entity class with just one string column and a primary key id column. We use special decorators to mark this as an entity class.

With all of the above steps complete, we can now tweak our Mikro ORM init function as below:

import { MikroORM } from '@mikro-orm/core';
import type { MySqlDriver } from '@mikro-orm/mysql';
import { Test } from './entities/test-entity';

const main = async() => {
    const orm = await MikroORM.init<MySqlDriver>()
    const em = orm.em.fork();
    const testentity = em.create(Test, {name: 'Name'})
    await em.persistAndFlush(testentity)
}

main().catch((error) => {
    console.error(error)
}).finally(() => {
    process.exit()
})

As you can notice, we no longer provide the configuration options in the MikroORM.init() call. When the application runs, it will automatically pick up the configuration from mikro-orm.config.ts file.

The rest of the code simply demonstrates how we can get an instance of the MikroORM Entity Manager and use it to create an instance of the Test entity. Lastly, we use persistAndFlush() to save the entity instance in the MySQL database.

3.1 – The MikroORM Fork Function

Note that the fork() function call is needed to provide a forked MikroORM Entity Manager. This way it can have its own IdentityMap. Alternatively, we can also add the property allowGlobalContext: true to the Mikro ORM config file.

3.2 – MikroORM Schema Generator

As discussed earlier, we can also generate the database schema and tables before running our program. To do so, we can use the MikroORM CLI to generate entities.

$ npx mikro-orm schema:create --run
$ npx mikro-orm generate-entities --run

Conclusion

The Mikro ORM Init Function is the first step to understand when we start with MikroORM with our NodeJS application. In this post, we have explored a couple of approaches to leverage the Init function and configure our database.

Want to use MikroORM to build a full fledged application? Check out this post on NestJS MikroORM.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: BlogMikroORM

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *