SuperAPI AI Directory

mikro-orm-v6-to-v7

Coding & development

View repository

Updated 10-16 07:23

About this skill

MikroORM v6 → v7 Migration Guide

Overview

MikroORM v7 is a major version upgrade. Core changes: native ESM, knex→kysely, decorator package split, minimum requirements of Node.js 22.17+/TypeScript 5.8+. This skill covers all critical paths of the migration to avoid common pitfalls.

Environment Requirements

Project v6 v7
Node.js 18+ 22.17+
TypeScript 5.0+ 5.8+
Module System CJS/ESM Native ESM

Migration Steps Overview

Step 1: Package Replacement

# 1. 替换核心包
pnpm remove @mikro-orm/knex
pnpm add @mikro-orm/sql

# 2. 安装装饰器包(如使用装饰器)
pnpm add @mikro-orm/decorators

# 3. SQLite 驱动选择(见 Edge-Ready 参考)
# better-sqlite3: pnpm add @mikro-orm/sqlite
# node:sqlite / bun:sqlite / D1: pnpm add @mikro-orm/sql kysely

Step 2: Import Path Updates

- import { Entity, PrimaryKey, Property } from '@mikro-orm/core';
+ import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
+ // 或 ES spec 装饰器:
+ // import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/es';

- import { ... } from '@mikro-orm/knex';
+ import { ... } from '@mikro-orm/sql';

Regarding the choice and configuration of ES vs Legacy decorators,must read references/decorators.md。

Step 3: API Replacement

- em.persistAndFlush(entity)
+ em.persist(entity).flush()

- em.removeAndFlush(entity)
+ em.remove(entity).flush()

- em.nativeInsert(Entity, data)
+ em.insert(Entity, data)

- em.getKnex()
+ em.getKysely()

- orm.getSchemaGenerator().createSchema()
+ orm.schema.create()

- em.find('User')
+ em.find(User)

- const orm = MikroORM.initSync({ ... })
+ const orm = new MikroORM({ ... })

For the complete API change comparison table, see references/api-changes.md。

Step 4: Entity Definition Adaptation

v7 provides two ways to define entities:

Approach A: defineEntity(recommended, new projects)

import { defineEntity, PrimaryKey, Property } from '@mikro-orm/core';

const UserEntity = defineEntity({
  class: class User {},
  tableName: 'user',
  properties: {
    id: p.uuid().primary(),
    name: p.string(),
    email: p.string().nullable(),
    createdAt: p.datetime().onCreate(() => new Date()),
  },
});

Approach B: Legacy decorators (migration of existing projects)

import { BaseEntity, type Opt } from '@mikro-orm/core';
import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';

@Entity({ tableName: 'user' })
export class User extends BaseEntity {
  @PrimaryKey({ type: 'uuid', onCreate: () => crypto.randomUUID() })
  id!: string & Opt;

  @Property({ type: 'text' })
  name!: string;

  @Property({ type: 'text', nullable: true })
  email?: string;
}

For a detailed comparison of the two approaches and scenario recommendations, see references/decorators.md。

Step 5: Default Value Change Check

Configuration Item v6 Default v7 Default Impact
Loading Strategy joined balanced to-many relations changed to separate queries
forceUtcTimezone false true Existing non-UTC data will be misinterpreted
Embedded Property Prefix absolute relative Nested embedded column names may change
@Transactional Propagation REQUIRES_NEW REQUIRED Joins existing transactions by default
processOnCreateHooksEarly false true onCreate Executes immediately in em.create Execute immediately in

Key: If existing data is stored in local time zones, before upgrading you must decide whether to migrate the data or explicitly set forceUtcTimezone: false。

Step 6: Edge/Bun/node:sqlite Adaptation

If you need to run MikroORM on Edge Runtime, Bun, or using node:sqlite Run MikroORM,must read references/edge-ready-sqlite.md。

Entity Definition Approach Selection

需要实体定义?
  ├─ 新项目 / 无历史 decorator 代码 → defineEntity(类型推断更好)
  ├─ 现有项目迁移 / 大量 decorator 实体 → Legacy decorator
  └─ TC39 decorator 环境(Node 22.6+原生支持)→ ES spec decorator

Quick Diagnosis of Common Errors

Symptom Cause Fix
Cannot find module '@mikro-orm/knex' Package Renaming Replace with @mikro-orm/sql
persistAndFlush is not a function API Removal em.persist(entity).flush()
nativeInsert is not a function Method Renaming em.insert(Entity, data)
Decorator SyntaxError (SWC/Vite) Decorator Compilation Not Configured See decorators.md
Value for X.id is required onCreate not configured PrimaryKey add onCreate
TypedArray.prototype.join incompatible Blob clone issue See known-issues.md
string reference not supported String Reference Removal Change to class reference () => Entity
Unexpected changes in Schema diff Default value changes Check the Step 5 default value table

For more known issues and solutions, see references/known-issues.md。

Migration Checklist

  • Node.js ≥ 22.17,TypeScript ≥ 5.8
  • @mikro-orm/knex → @mikro-orm/sql
  • Install @mikro-orm/decorators, update imports
  • Replace persistAndFlush / removeAndFlush
  • Replace string references with class references
  • Update SchemaGenerator / Migrator / Seeder method names
  • QueryBuilder .execute() / .getResult() Replace direct await
  • Update driverOptions Remove connection nesting
  • Check forceUtcTimezone impact on existing data
  • Update Formula/Index/Check callback signatures (quote helper functions)
  • Run orm.schema.update({ diff: true }) to check schema changes
  • Run typecheck and tests to verify

Reference Documentation