mikro-orm for TypeScript: complete guide with examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course
\n

mikro-orm for TypeScript: complete guide with examples

\n\n
\n

1. What is it and why is it needed?

\n

\nMikro-ORM is a modern object-relational library (ORM) for TypeScript and JavaScript (Node.js) that implements the Identity Map and Unit of Work patterns. Unlike classic ORMs like TypeORM or Sequelize, Mikro-ORM is inspired by Doctrine (PHP) and Hibernate (Java) and offers more predictable management of entity state and their synchronization with the database.\n

\n

\nWhy is it needed? In typical web applications, developers often face the problem of "dirty" data, when the same record is loaded twice in different parts of the code, leading to conflicts during saving. Mikro-ORM solves this problem with Identity Map: for each primary key, there is exactly one instance of the entity within a single context (EntityManager). This ensures that you always work with the current version of the object, and all changes are tracked automatically.\n

\n

\nThe library supports many DBMS (PostgreSQL, MySQL, SQLite, MongoDB, MariaDB) and provides powerful tools: migrations, built-in transaction support, cascade operations, relation loading (eager/lazy), built-in schema validator, and entity generator from an existing database. Mikro-ORM is ideal for complex domain models and microservice architecture where data consistency is important.\n

\n
\n\n
\n

2. Installation

\n

To install Mikro-ORM and the required database driver, run the command via npm (or yarn/pnpm):

\n
# Install the core library\nnpm install @mikro-orm/core\n\n# Install the driver for your DB (choose one):\nnpm install @mikro-orm/sqlite    # SQLite\nnpm install @mikro-orm/postgresql # PostgreSQL\nnpm install @mikro-orm/mysql      # MySQL / MariaDB\nnpm install @mikro-orm/mongodb    # MongoDB\n\n# Additional: CLI for migrations and schema generation\nnpm install @mikro-orm/cli\nnpm install @mikro-orm/migrations  # for migrations\n
\n

It is also recommended to install reflect-metadata for decorators to work:

\n
npm install reflect-metadata\n
\n

Add to tsconfig.json:

\n
{\n  "compilerOptions": {\n    "experimentalDecorators": true,\n    "emitDecoratorMetadata": true,\n    "target": "ES2021",\n    "module": "commonjs"\n  }\n}\n
\n
\n\n
\n

3. Quick start — minimal working example

\n

Let's create a simple application on SQLite with one entity User.

\n\n

Step 1. Define the entity (entities/User.ts):

\n
import { Entity, PrimaryKey, Property } from '@mikro-orm/core';\n\n@Entity()\nexport class User {\n  @PrimaryKey()\n  id!: number;\n\n  @Property()\n  name!: string;\n\n  @Property()\n  email!: string;\n\n  @Property()\n  createdAt: Date = new Date();\n}\n
\n\n

Step 2. Configure Mikro-ORM (index.ts):

\n
import 'reflect-metadata';\nimport { MikroORM } from '@mikro-orm/core';\nimport { SqliteDriver } from '@mikro-orm/sqlite';\nimport { User } from './entities/User';\n\nasync function main() {\n  const orm = await MikroORM.init({\n    entities: [User],\n    dbName: 'test.db',\n    driver: SqliteDriver,\n    debug: true, // SQL query logging\n  });\n\n  // Create schema (in dev mode)\n  await orm.getSchemaGenerator().createSchema();\n\n  // Get EntityManager\n  const em = orm.em.fork();\n\n  // Create a user\n  const user = em.create(User, {\n    name: 'Ivan',\n    email: 'ivan@example.com',\n  });\n  await em.flush(); // save to DB\n\n  // Read the user\n  const found = await em.findOne(User, { emai                    

Recommendations