# MikroORM for Node.js [MikroORM](https://mikro-orm.io/) is a TypeScript ORM for Node.js built around the **Data Mapper**, **Unit of Work**, and **Identity Map** patterns. It provides a type-safe persistence layer while allowing application services to remain independent of database access details when it is used behind repository interfaces. This page summarizes the MikroORM architecture and repository approach documented in [`mikro-orm-repo-pattern.md`](./mikro-orm-repo-pattern.md), with particular attention to PostgreSQL-backed Node APIs. ## Reference implementation - [spinningideas/mikro-orm-poc](https://github.com/spinningideas/mikro-orm-poc) — Reference implementation of a Node API using MikroORM and PostgreSQL DB. ## Why use MikroORM? MikroORM is a good fit when a Node.js application needs: - TypeScript entities and strongly typed database access - Data Mapper rather than Active Record coupling - Unit-of-Work change tracking and coordinated flushes - Identity-map behavior within an EntityManager context - Repository-based access to entities - PostgreSQL and other relational database drivers - Transactions, relation criteria, pagination, and migrations - A persistence adapter that can be placed behind an ORM-neutral application port The repository-pattern approach is important when the application may later move from MikroORM to another adapter such as Drizzle or an in-memory implementation. Services should depend on `IBaseRepository` or `IRepositoryProvider`, not directly on MikroORM's `EntityManager`. ## Core MikroORM concepts ### Entities Entities are TypeScript classes that represent persisted domain data, such as: - `User` - `Account` - `Verification` The entity class is supplied to a repository or EntityManager so MikroORM can map object operations to database operations. ### EntityManager The `EntityManager` is MikroORM's main unit-of-work API. It is used for operations such as: - `findOne` - `findAndCount` - `create` - `persist` - `flush` - `nativeUpdate` - `nativeDelete` - `transactional` The EntityManager tracks managed entities and coordinates persistence. It also provides the context in which identity-map behavior and transactions operate. ### EntityRepository `EntityRepository` provides entity-specific access for a mapped type. The documented implementation extends it with `MikroOrmBaseRepository` so callers can use the ORM-neutral repository contract while specialized repositories can still access MikroORM capabilities when necessary. A domain repository can add business-specific queries without exposing MikroORM to the rest of the application: ```ts export class UserRepository extends MikroOrmBaseRepository { async findByEmail(email: string): Promise { return this.findOne({ email }); } } ``` ### Request context and EntityManager lifetime The application uses `RequestContext` backed by `AsyncLocalStorage` to make the current EntityManager available during a web request. `Database.getEm()` returns: - The request-scoped EntityManager inside a request - A fresh `orm.em.fork()` outside a request This is essential for request isolation, identity-map behavior, and transaction correctness. ## The critical lifetime rule: resolve lazily A repository must not capture an EntityManager once and keep it for the lifetime of a long-lived service. This is unsafe: ```ts // Do not capture a request-dependent EM at application startup. const repo = new MikroOrmBaseRepository({ em: Database.getEm() }, UserEntity); ``` The service may be instantiated when no request context exists, or it may retain a startup fork and silently bypass later request contexts. Instead, resolve the repository or EntityManager lazily for each operation: ```ts const users = (): IBaseRepository => new MikroOrmBaseRepository({ em: Database.getEm() }, UserEntity); const user = await users().findOneWhere({ userId }); ``` This pattern is especially important when a service is created once during application startup but serves many requests. ## Repository boundary The recommended architecture has three layers: ```text Application service | v ORM-neutral repository port (IBaseRepository / IRepositoryProvider) | v MikroORM adapter (MikroOrmBaseRepository) | v MikroORM EntityManager + PostgreSQL ``` ### `IBaseRepository` `IBaseRepository` is the application-facing port. Its signatures should not expose MikroORM types such as `FilterQuery`, `EntityData`, `RequiredEntityData`, or `UpsertOptions`. Instead, the port uses neutral types that another adapter can implement: - `CriteriaShape` for queries - `NewEntityData` for creation - `FindOneOptions` for refresh and populate behavior - Neutral upsert options This creates a real seam for: - MikroORM in production - An in-memory repository in unit tests - A future Drizzle adapter - Other persistence implementations without changing service logic ### `IRepositoryProvider` For larger applications, a provider can resolve repositories on demand: ```ts export interface IRepositoryProvider { repoFor(entity: EntityRef): IBaseRepository; } ``` The MikroORM implementation creates a repository using the current `Database.getEm()` when the provider is called. A service then depends on the provider rather than importing `Database` or constructing repositories itself. ## Criteria DSL The repository port uses a plain-object `CriteriaShape` DSL rather than leaking MikroORM's `FilterQuery` type. ```ts { email: "a@b.c" } // equality { roleId: ids } // array shorthand for $in { email: { $ilike: "%example%" } } // operator map { lease: { facilityId } } // nested relation criteria { $or: [{ email: term }, { name: term }] } // combinator ``` Supported operators include: - `$eq` - `$ne` - `$in` - `$nin` - `$gt` - `$gte` - `$lt` - `$lte` - `$like` - `$ilike` The MikroORM adapter translates this neutral criteria into `FilterQuery` values and rejects unsupported `$` operators. The same criteria can be interpreted by an in-memory fake or translated to another database library. A fluent `Criteria` builder is available when optional filters or compound conditions are needed. It can omit empty values such as `undefined`, empty strings, and empty arrays, and compose `and`, `or`, and `not` conditions. ## Repository operation mapping | Direct EntityManager operation | Repository operation | Use | | --- | --- | --- | | `em.findOne(Entity, criteria)` | `findOneWhere(criteria, options?)` | Find one entity; supports `refresh` and `populate` options | | `em.findAndCount(...)` | `search(...)` | Search, sort, and paginate through a repository method | | `em.create(...)` + `persist().flush()` | `createNew(data)` | Create and immediately flush one entity | | `em.nativeUpdate(...)` | `nativeUpdateWhere(criteria, patch)` | Efficient bulk/single update returning affected count | | Load, assign, and flush | `updateWhere(criteria, patch)` | Tracked update returning the entity or `null` | | `em.nativeDelete(...)` | `deleteWhere(criteria)` | Delete matching entities and return deleted count | The distinction between `nativeUpdateWhere` and `updateWhere` is intentional: - `nativeUpdateWhere` performs a direct SQL-style update and returns a count. - `updateWhere` loads the entity, applies changes, and flushes through the Unit of Work. ## Transactions Multi-entity operations should use a transaction. A user-creation workflow, for example, can write: 1. `User` 2. `Verification` 3. `Account` If each write flushes independently, a failure in the middle can leave partial data. The repository port therefore exposes: ```ts transactional(work: () => Promise): Promise; ``` The MikroORM adapter implements this with `em.transactional(...)` and rebinds the transactional EntityManager into `RequestContext` so repositories resolved inside the callback participate in the same transaction. A future Drizzle adapter can implement the same contract with `db.transaction(work)`. ## Search and pagination The repository abstraction can standardize common search behavior instead of allowing each service to construct ORM queries directly. The documented `search` method supports: - A selected searchable field - A search term - Sort field and direction - Page size - Page number - A total result count and paged data For PostgreSQL, the documented user search uses case-insensitive `$ilike` matching while keeping the query behind the repository boundary. ## Testing strategy The repository port makes service tests independent of PostgreSQL and MikroORM. An in-memory implementation can interpret the same `CriteriaShape` contract: ```ts const service = new UsersService({ users: () => userRepositoryFake, accounts: () => accountRepositoryFake, verifications: () => verificationRepositoryFake, }); ``` This enables tests for service behavior without: - Starting PostgreSQL - Creating MikroORM metadata - Mocking `Database.getEm()` - Depending on SQL details The key requirement is that the fake and the MikroORM adapter honor the same repository semantics, especially for criteria operators, update return values, delete counts, and transactions. ## Recommended adoption path 1. Create domain repositories for the entities that need custom methods. 2. Keep `IBaseRepository` ORM-neutral. 3. Migrate service calls from `Database.getEm()` to repository methods. 4. Use lazy repository factories or an `IRepositoryProvider` so request-scoped EntityManagers are never captured too early. 5. Wrap multi-write operations in `transactional()`. 6. Add in-memory repository fakes for service tests. 7. Introduce a DI container only if the service graph becomes too large for hand-wired providers. 8. Keep the PostgreSQL/MikroORM adapter isolated so another persistence implementation can be introduced later. ## Important implementation issue The source analysis identifies an email-conflict bug in `updateUser`. A query shaped like this checks the email and the same user's ID: ```ts { email: userData.email, userId } ``` That cannot find a different user with the same email. The conflict query should search by email alone and then compare the returned `userId` with the user being updated. ## Related pages - [Node ORMs](./Node-ORMs.md) - [Repository interfaces](./Repository-Interfaces.md) - [Repositories](./Repositories.md) - [Node dependency injection](./Node-dependency-injection.md)