Skip to content

Node ORM MikroOrm

Spinning Idea edited this page Sep 28, 2026 · 1 revision

MikroORM for Node.js

MikroORM 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, with particular attention to PostgreSQL-backed Node APIs.

Reference implementation

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<T> provides entity-specific access for a mapped type. The documented implementation extends it with MikroOrmBaseRepository<T> 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:

export class UserRepository extends MikroOrmBaseRepository<UserEntity> {
  async findByEmail(email: string): Promise<UserEntity | null> {
    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:

// 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:

const users = (): IBaseRepository<UserEntity> =>
  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:

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<M> for queries
  • NewEntityData<M> for creation
  • FindOneOptions<M> 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:

export interface IRepositoryProvider {
  repoFor<T extends object>(entity: EntityRef<T>): IBaseRepository<T>;
}

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<M> DSL rather than leaking MikroORM's FilterQuery type.

{ 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<M> 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:

transactional<R>(work: () => Promise<R>): Promise<R>;

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:

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:

{ 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

Clone this wiki locally