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: 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.4license: Apache-2.05---67# MikroORM — TypeScript ORM with Unit of Work89You 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.1011## Core Capabilities1213### Entity Definition1415```typescript16import { Entity, PrimaryKey, Property, ManyToOne, OneToMany, Collection,17 Enum, Index, Unique, Embeddable, Embedded, Filter } from "@mikro-orm/core";18import { v4 } from "uuid";1920@Embeddable()21class Address {22 @Property()23 street: string;2425 @Property()26 city: string;2728 @Property()29 country: string;30}3132@Entity()33@Filter({ name: "active", cond: { deletedAt: null }, default: true })34export class User {35 @PrimaryKey()36 id: string = v4();3738 @Property()39 name: string;4041 @Index()42 @Unique()43 @Property()44 email: string;4546 @Enum(() => UserRole)47 role: UserRole = UserRole.USER;4849 @Embedded(() => Address, { nullable: true })50 address?: Address;5152 @OneToMany(() => Post, (post) => post.author)53 posts = new Collection<Post>(this);5455 @Property()56 createdAt: Date = new Date();5758 @Property({ onUpdate: () => new Date() })59 updatedAt: Date = new Date();6061 @Property({ nullable: true })62 deletedAt?: Date;63}6465enum UserRole { USER = "user", ADMIN = "admin" }6667@Entity()68export class Post {69 @PrimaryKey()70 id: string = v4();7172 @Property()73 title: string;7475 @Property({ type: "text" })76 body: string;7778 @Property()79 published: boolean = false;8081 @ManyToOne(() => User)82 author: User;8384 @Property()85 createdAt: Date = new Date();86}87```8889### Unit of Work (Auto Change Tracking)9091```typescript92import { MikroORM, RequestContext } from "@mikro-orm/core";9394const orm = await MikroORM.init({95 entities: [User, Post],96 dbName: "myapp",97 type: "postgresql",98 debug: process.env.NODE_ENV === "development",99});100101// Express middleware — one EntityManager per request102app.use((req, res, next) => {103 RequestContext.create(orm.em, next);104});105106// Usage — automatic change tracking107app.put("/users/:id", async (req, res) => {108 const em = orm.em;109 const user = await em.findOneOrFail(User, req.params.id);110111 user.name = req.body.name; // Just modify the entity112 user.email = req.body.email;113114 await em.flush(); // MikroORM detects changes, generates UPDATE115 res.json(user);116});117118// Identity Map — same entity loaded twice returns same reference119const user1 = await em.findOne(User, "abc");120const user2 = await em.findOne(User, "abc");121console.log(user1 === user2); // true — same object in memory122123// QueryBuilder124const topAuthors = await em.createQueryBuilder(User, "u")125 .select(["u.*", "count(p.id) as post_count"])126 .leftJoin("u.posts", "p")127 .where({ role: UserRole.ADMIN })128 .groupBy("u.id")129 .orderBy({ post_count: "DESC" })130 .limit(10)131 .getResultList();132```133134## Installation135136```bash137npm install @mikro-orm/core @mikro-orm/postgresql @mikro-orm/cli138npx mikro-orm migration:create139npx mikro-orm migration:up140```141142## Best Practices1431441. **Unit of Work** — Modify entities directly; call `em.flush()` once to batch all changes into minimal SQL1452. **Identity Map** — Same entity loaded twice returns same reference; prevents inconsistency in a request1463. **RequestContext** — Use `RequestContext.create()` middleware; gives each request its own EntityManager1474. **Filters** — Use `@Filter` for soft deletes, multi-tenancy; applied automatically to all queries1485. **Embeddables** — Use `@Embedded` for value objects (Address, Money); stored in same table, typed as objects1496. **Populate** — Explicitly populate relations: `em.find(User, {}, { populate: ['posts'] })`; no implicit lazy loading1507. **Migrations** — Use CLI to generate migrations from entity changes; review SQL before running1518. **Serialization** — Use `wrap(entity).toJSON()` or custom serializers; control what's exposed in API responses