MikroORM — TypeScript ORM with Unit of Work
You are an expert in MikroORM, the TypeScript ORM built on Unit of Work and Identity Map patterns. You help developers build data layers with decorator-based entities, automatic change tracking, lazy/eager loading, embeddables, query builder, migrations, and seeding — supporting PostgreSQL, MySQL, SQLite, and MongoDB with a DDD-friendly architecture.
Core Capabilities
Entity Definition
import { Entity, PrimaryKey, Property, ManyToOne, OneToMany, Collection,
Enum, Index, Unique, Embeddable, Embedded, Filter } from "@mikro-orm/core";
import { v4 } from "uuid";
@Embeddable()
class Address {
@Property()
street: string;
@Property()
city: string;
@Property()
country: string;
}
@Entity()
@Filter({ name: "active", cond: { deletedAt: null }, default: true })
export class User {
@PrimaryKey()
id: string = v4();
@Property()
name: string;
@Index()
@Unique()
@Property()
email: string;
@Enum(() => UserRole)
role: UserRole = UserRole.USER;
@Embedded(() => Address, { nullable: true })
address?: Address;
@OneToMany(() => Post, (post) => post.author)
posts = new Collection<Post>(this);
@Property()
createdAt: Date = new Date();
@Property({ onUpdate: () => new Date() })
updatedAt: Date = new Date();
@Property({ nullable: true })
deletedAt?: Date;
}
enum UserRole { USER = "user", ADMIN = "admin" }
@Entity()
export class Post {
@PrimaryKey()
id: string = v4();
@Property()
title: string;
@Property({ type: "text" })
body: string;
@Property()
published: boolean = false;
@ManyToOne(() => User)
author: User;
@Property()
createdAt: Date = new Date();
}
Unit of Work (Auto Change Tracking)
import { MikroORM, RequestContext } from "@mikro-orm/core";
const orm = await MikroORM.init({
entities: [User, Post],
dbName: "myapp",
type: "postgresql",
debug: process.env.NODE_ENV === "development",
});
// Express middleware — one EntityManager per request
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
// Usage — automatic change tracking
app.put("/users/:id", async (req, res) => {
const em = orm.em;
const user = await em.findOneOrFail(User, req.params.id);
user.name = req.body.name; // Just modify the entity
user.email = req.body.email;
await em.flush(); // MikroORM detects changes, generates UPDATE
res.json(user);
});
// Identity Map — same entity loaded twice returns same reference
const user1 = await em.findOne(User, "abc");
const user2 = await em.findOne(User, "abc");
console.log(user1 === user2); // true — same object in memory
// QueryBuilder
const topAuthors = await em.createQueryBuilder(User, "u")
.select(["u.*", "count(p.id) as post_count"])
.leftJoin("u.posts", "p")
.where({ role: UserRole.ADMIN })
.groupBy("u.id")
.orderBy({ post_count: "DESC" })
.limit(10)
.getResultList();
Installation
npm install @mikro-orm/core @mikro-orm/postgresql @mikro-orm/cli
npx mikro-orm migration:create
npx mikro-orm migration:up
Best Practices
- Unit of Work — Modify entities directly; call
em.flush() once to batch all changes into minimal SQL
- Identity Map — Same entity loaded twice returns same reference; prevents inconsistency in a request
- RequestContext — Use
RequestContext.create() middleware; gives each request its own EntityManager
- Filters — Use
@Filter for soft deletes, multi-tenancy; applied automatically to all queries
- Embeddables — Use
@Embedded for value objects (Address, Money); stored in same table, typed as objects
- Populate — Explicitly populate relations:
em.find(User, {}, { populate: ['posts'] }); no implicit lazy loading
- Migrations — Use CLI to generate migrations from entity changes; review SQL before running
- Serialization — Use
wrap(entity).toJSON() or custom serializers; control what's exposed in API responses
1---2name: mikro-orm3description: >-4 You are an expert in MikroORM, the TypeScript ORM built on Unit of Work and5 Identity Map patterns. You help developers build data layers with6 decorator-based entities, automatic change tracking, lazy/eager loading,7 embeddables, query builder, migrations, and seeding — supporting PostgreSQL,8 MySQL, SQLite, and MongoDB with a DDD-friendly architecture.9license: Apache-2.010compatibility: ''11metadata:12 source: https://skillmd.com/skills/eliferjunior/mikro-orm13 author: terminal-skills14 version: 1.0.015 category: Backend Development16 tags:17 - orm18 - typescript19 - database20 - unit-of-work21 - identity-map22 - sql23 - mongodb24---2526# MikroORM — TypeScript ORM with Unit of Work2728You are an expert in MikroORM, the TypeScript ORM built on Unit of Work and Identity Map patterns. You help developers build data layers with decorator-based entities, automatic change tracking, lazy/eager loading, embeddables, query builder, migrations, and seeding — supporting PostgreSQL, MySQL, SQLite, and MongoDB with a DDD-friendly architecture.2930## Core Capabilities3132### Entity Definition3334```typescript35import { Entity, PrimaryKey, Property, ManyToOne, OneToMany, Collection,36 Enum, Index, Unique, Embeddable, Embedded, Filter } from "@mikro-orm/core";37import { v4 } from "uuid";3839@Embeddable()40class Address {41 @Property()42 street: string;4344 @Property()45 city: string;4647 @Property()48 country: string;49}5051@Entity()52@Filter({ name: "active", cond: { deletedAt: null }, default: true })53export class User {54 @PrimaryKey()55 id: string = v4();5657 @Property()58 name: string;5960 @Index()61 @Unique()62 @Property()63 email: string;6465 @Enum(() => UserRole)66 role: UserRole = UserRole.USER;6768 @Embedded(() => Address, { nullable: true })69 address?: Address;7071 @OneToMany(() => Post, (post) => post.author)72 posts = new Collection<Post>(this);7374 @Property()75 createdAt: Date = new Date();7677 @Property({ onUpdate: () => new Date() })78 updatedAt: Date = new Date();7980 @Property({ nullable: true })81 deletedAt?: Date;82}8384enum UserRole { USER = "user", ADMIN = "admin" }8586@Entity()87export class Post {88 @PrimaryKey()89 id: string = v4();9091 @Property()92 title: string;9394 @Property({ type: "text" })95 body: string;9697 @Property()98 published: boolean = false;99100 @ManyToOne(() => User)101 author: User;102103 @Property()104 createdAt: Date = new Date();105}106```107108### Unit of Work (Auto Change Tracking)109110```typescript111import { MikroORM, RequestContext } from "@mikro-orm/core";112113const orm = await MikroORM.init({114 entities: [User, Post],115 dbName: "myapp",116 type: "postgresql",117 debug: process.env.NODE_ENV === "development",118});119120// Express middleware — one EntityManager per request121app.use((req, res, next) => {122 RequestContext.create(orm.em, next);123});124125// Usage — automatic change tracking126app.put("/users/:id", async (req, res) => {127 const em = orm.em;128 const user = await em.findOneOrFail(User, req.params.id);129130 user.name = req.body.name; // Just modify the entity131 user.email = req.body.email;132133 await em.flush(); // MikroORM detects changes, generates UPDATE134 res.json(user);135});136137// Identity Map — same entity loaded twice returns same reference138const user1 = await em.findOne(User, "abc");139const user2 = await em.findOne(User, "abc");140console.log(user1 === user2); // true — same object in memory141142// QueryBuilder143const topAuthors = await em.createQueryBuilder(User, "u")144 .select(["u.*", "count(p.id) as post_count"])145 .leftJoin("u.posts", "p")146 .where({ role: UserRole.ADMIN })147 .groupBy("u.id")148 .orderBy({ post_count: "DESC" })149 .limit(10)150 .getResultList();151```152153## Installation154155```bash156npm install @mikro-orm/core @mikro-orm/postgresql @mikro-orm/cli157npx mikro-orm migration:create158npx mikro-orm migration:up159```160161## Best Practices1621631. **Unit of Work** — Modify entities directly; call `em.flush()` once to batch all changes into minimal SQL1642. **Identity Map** — Same entity loaded twice returns same reference; prevents inconsistency in a request1653. **RequestContext** — Use `RequestContext.create()` middleware; gives each request its own EntityManager1664. **Filters** — Use `@Filter` for soft deletes, multi-tenancy; applied automatically to all queries1675. **Embeddables** — Use `@Embedded` for value objects (Address, Money); stored in same table, typed as objects1686. **Populate** — Explicitly populate relations: `em.find(User, {}, { populate: ['posts'] })`; no implicit lazy loading1697. **Migrations** — Use CLI to generate migrations from entity changes; review SQL before running1708. **Serialization** — Use `wrap(entity).toJSON()` or custom serializers; control what's exposed in API responses