### Clone Schema-First Guide Project Source: https://mikro-orm.io/docs/next/schema-first-guide Clone the example project from GitHub to view the final application structure. ```bash git clone https://github.com/mikro-orm/schema-first-guide.git ``` -------------------------------- ### Install @mikro-orm/decorators with Bun Source: https://mikro-orm.io/docs/next/upgrading-v6-to-v7 Install the separate `@mikro-orm/decorators` package for MikroORM v7. This example shows the Bun installation command. ```bash bun add @mikro-orm/decorators ``` -------------------------------- ### Clone MikroORM Guide Repository Source: https://mikro-orm.io/docs/next/guide Clone the GitHub repository to get a working example of the final project that will be built throughout this guide. ```bash git clone https://github.com/mikro-orm/guide.git ``` -------------------------------- ### Install reflect-metadata with Bun Source: https://mikro-orm.io/docs/next/using-decorators Install the `reflect-metadata` package using Bun. ```bash bun add reflect-metadata ``` -------------------------------- ### Install @mikro-orm/libsql with Bun Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package and the libSQL driver using Bun. ```bash bun add @mikro-orm/core @mikro-orm/libsql ``` -------------------------------- ### Install @mikro-orm/decorators with pnpm Source: https://mikro-orm.io/docs/next/upgrading-v6-to-v7 Install the separate `@mikro-orm/decorators` package for MikroORM v7. This example shows the pnpm installation command. ```bash pnpm add @mikro-orm/decorators ``` -------------------------------- ### Install Framework Plugins Source: https://mikro-orm.io/docs/next/usage-with-adminjs Install the necessary plugin and peer dependencies for your chosen web framework. ```bash $ yarn add @adminjs/express # Peer dependencies $ yarn add express express-formidable express-session ``` ```bash $ yarn add @adminjs/hapi # Peer dependencies $ yarn add @hapi/boom @hapi/cookie @hapi/hapi @hapi/inert ``` -------------------------------- ### Install @mikro-orm/decorators with Yarn Source: https://mikro-orm.io/docs/next/upgrading-v6-to-v7 Install the separate `@mikro-orm/decorators` package for MikroORM v7. This example shows the Yarn installation command. ```bash yarn add @mikro-orm/decorators ``` -------------------------------- ### Install @mikro-orm/libsql with npm Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package and the libSQL driver using npm. ```bash npm install @mikro-orm/core @mikro-orm/libsql ``` -------------------------------- ### Install Core Dependencies with Bun Source: https://mikro-orm.io/docs/next/schema-first-guide Installs MikroORM core, MySQL driver, migrations, and Fastify using Bun. ```bash bun add @mikro-orm/core \ @mikro-orm/mysql \ @mikro-orm/migrations \ fastify ``` -------------------------------- ### Install MikroORM Adapter and Drivers Source: https://mikro-orm.io/docs/next/usage-with-adminjs Install the adapter and the specific database driver required for your project. ```bash $ yarn add @adminjs/mikroorm # A MikroORM driver and core package, choose the one which suits you: $ yarn add @mikro-orm/core @mikro-orm/mongodb # for mongo $ yarn add @mikro-orm/core @mikro-orm/mysql # for mysql $ yarn add @mikro-orm/core @mikro-orm/mariadb # for mariadb $ yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql $ yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite ``` -------------------------------- ### Install @mikro-orm/libsql with Yarn Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package and the libSQL driver using Yarn. ```bash yarn add @mikro-orm/core @mikro-orm/libsql ``` -------------------------------- ### Execute Production Build and Start Source: https://mikro-orm.io/docs/next/guide/advanced Commands to create a bundled production build using Vite and then start the application. ```bash npm run bundle npm run start:prod ``` -------------------------------- ### Install @mikro-orm/sql with Bun Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package, the generic SQL driver, and Kysely using Bun. ```bash bun add @mikro-orm/core @mikro-orm/sql kysely ``` -------------------------------- ### Install @mikro-orm/sqlite with Bun Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package and the SQLite driver using Bun. ```bash bun add @mikro-orm/core @mikro-orm/sqlite ``` -------------------------------- ### Install Core Dependencies with npm Source: https://mikro-orm.io/docs/next/schema-first-guide Installs MikroORM core, MySQL driver, migrations, and Fastify using npm. ```bash npm install @mikro-orm/core \ @mikro-orm/mysql \ @mikro-orm/migrations \ fastify ``` -------------------------------- ### Install @mikro-orm/decorators package Source: https://mikro-orm.io/docs/next/upgrading-v6-to-v7 Install the separate `@mikro-orm/decorators` package for MikroORM v7. This example shows the npm installation command. ```bash npm install @mikro-orm/decorators ``` -------------------------------- ### Install Core Dependencies with pnpm Source: https://mikro-orm.io/docs/next/schema-first-guide Installs MikroORM core, MySQL driver, migrations, and Fastify using pnpm. ```bash pnpm add @mikro-orm/core \ @mikro-orm/mysql \ @mikro-orm/migrations \ fastify ``` -------------------------------- ### Install @mikro-orm/libsql with pnpm Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package and the libSQL driver using pnpm. ```bash pnpm add @mikro-orm/core @mikro-orm/libsql ``` -------------------------------- ### Install reflect-metadata with npm Source: https://mikro-orm.io/docs/next/using-decorators Install the `reflect-metadata` package using npm. ```bash npm install reflect-metadata ``` -------------------------------- ### Install reflect-metadata with Yarn Source: https://mikro-orm.io/docs/next/using-decorators Install the `reflect-metadata` package using Yarn. ```bash yarn add reflect-metadata ``` -------------------------------- ### Install reflect-metadata with pnpm Source: https://mikro-orm.io/docs/next/using-decorators Install the `reflect-metadata` package using pnpm. ```bash pnpm add reflect-metadata ``` -------------------------------- ### Define Entities and Initialize Mikro-ORM (Decorators) Source: https://mikro-orm.io/docs/next/usage-with-cockroachdb This example shows entity definition using decorators and initializing Mikro-ORM with PostgreSQL driver for CockroachDB. It covers entity creation, persistence, and querying with population. Verify connection details and driver setup. ```typescript @Entity() class Author { @PrimaryKey({ type: 'uuid' }) id: string = v4(); @Property() name!: string; @Property() email!: string; @OneToMany(() => Book, book => book.author) books = new Collection(this); } @Entity() class Book { @PrimaryKey({ type: 'uuid' }) id: string = v4(); @Property() title!: string; @ManyToOne(() => Author) author!: Author; } const orm = await MikroORM.init({ entities: [Author, Book], driver: PostgreSqlDriver, metadataProvider: ReflectMetadataProvider, dbName: 'my_database', host: 'localhost', port: 26257, user: 'root', password: '', }); await orm.schema.update(); const em = orm.em.fork(); const author = em.create(Author, { name: 'John', email: 'john@example.com' }); em.create(Book, { title: 'My Book', author }); await em.flush(); const books = await em.find(Book, {}, { populate: ['author'] }); console.log(books[0].author.name); // 'John' await orm.close(); ``` -------------------------------- ### Install development dependencies Source: https://mikro-orm.io/docs/next/guide/first-entity Install CLI, TypeScript, and testing tools required for development. ```bash npm install --save-dev @mikro-orm/cli \ typescript \ tsx \ @types/node \ vitest ``` ```bash yarn add --dev @mikro-orm/cli \ typescript \ tsx \ @types/node \ vitest ``` ```bash pnpm add --save-dev @mikro-orm/cli \ typescript \ tsx \ @types/node \ vitest ``` ```bash bun add --dev @mikro-orm/cli \ typescript \ tsx \ @types/node \ vitest ``` -------------------------------- ### Install @mikro-orm/sql with npm Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package, the generic SQL driver, and Kysely using npm. ```bash npm install @mikro-orm/core @mikro-orm/sql kysely ``` -------------------------------- ### Install project dependencies Source: https://mikro-orm.io/docs/next/guide/first-entity Install core MikroORM and Fastify dependencies using various package managers. ```bash npm install @mikro-orm/core \ @mikro-orm/sqlite \ fastify ``` ```bash yarn add @mikro-orm/core \ @mikro-orm/sqlite \ fastify ``` ```bash pnpm add @mikro-orm/core \ @mikro-orm/sqlite \ fastify ``` ```bash bun add @mikro-orm/core \ @mikro-orm/sqlite \ fastify ``` -------------------------------- ### Install MikroORM PostgreSQL Driver with Bun Source: https://mikro-orm.io/docs/next/usage-with-cockroachdb Install the core MikroORM package and the PostgreSQL driver using Bun. ```bash bun add @mikro-orm/core @mikro-orm/postgresql ``` -------------------------------- ### Install @mikro-orm/sql with D1 for Bun Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install necessary packages for Cloudflare D1 integration using Bun. ```bash bun add @mikro-orm/core @mikro-orm/sql kysely kysely-d1 ``` -------------------------------- ### Install @mikro-orm/sql with Yarn Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package, the generic SQL driver, and Kysely using Yarn. ```bash yarn add @mikro-orm/core @mikro-orm/sql kysely ``` -------------------------------- ### Install Fastify JWT (Bun) Source: https://mikro-orm.io/docs/next/schema-first-guide Installs the @fastify/jwt package using Bun. ```bash bun add @fastify/jwt ``` -------------------------------- ### Install @mikro-orm/sqlite with npm Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package and the SQLite driver using npm. ```bash npm install @mikro-orm/core @mikro-orm/sqlite ``` -------------------------------- ### Install MikroORM PostgreSQL Driver with npm Source: https://mikro-orm.io/docs/next/usage-with-cockroachdb Install the core MikroORM package and the PostgreSQL driver using npm. ```bash npm install @mikro-orm/core @mikro-orm/postgresql ``` -------------------------------- ### Install @mikro-orm/sqlite with pnpm Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package and the SQLite driver using pnpm. ```bash pnpm add @mikro-orm/core @mikro-orm/sqlite ``` -------------------------------- ### Install @mikro-orm/sql with pnpm Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package, the generic SQL driver, and Kysely using pnpm. ```bash pnpm add @mikro-orm/core @mikro-orm/sql kysely ``` -------------------------------- ### Install Core Dependencies with Yarn Source: https://mikro-orm.io/docs/next/schema-first-guide Installs MikroORM core, MySQL driver, migrations, and Fastify using Yarn. ```bash yarn add @mikro-orm/core \ @mikro-orm/mysql \ @mikro-orm/migrations \ fastify ``` -------------------------------- ### Install @mikro-orm/sqlite with Yarn Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install the core MikroORM package and the SQLite driver using Yarn. ```bash yarn add @mikro-orm/core @mikro-orm/sqlite ``` -------------------------------- ### Install canary builds Source: https://mikro-orm.io/docs/next/canary-builds Use specific dist-tags to install canary versions of MikroORM packages. ```bash npm install @mikro-orm/core@next-v7 @mikro-orm/mysql@next-v7 # or yarn add @mikro-orm/core@next-v7 @mikro-orm/mysql@next-v7 ``` -------------------------------- ### Install MikroORM Reflection Package Source: https://mikro-orm.io/docs/next/using-decorators Install the necessary reflection package for MikroORM using npm, Yarn, pnpm, or Bun. ```bash npm install @mikro-orm/reflection ``` ```bash yarn add @mikro-orm/reflection ``` ```bash pnpm add @mikro-orm/reflection ``` ```bash bun add @mikro-orm/reflection ``` -------------------------------- ### Install @mikro-orm/sql with D1 for npm Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install necessary packages for Cloudflare D1 integration using npm. ```bash npm install @mikro-orm/core @mikro-orm/sql kysely kysely-d1 ``` -------------------------------- ### Install MikroORM Migrations Package Source: https://mikro-orm.io/docs/next/guide/project-setup Install the necessary migrations package for your SQL driver using npm, Yarn, pnpm, or Bun. ```bash npm install @mikro-orm/migrations ``` ```bash yarn add @mikro-orm/migrations ``` ```bash pnpm add @mikro-orm/migrations ``` ```bash bun add @mikro-orm/migrations ``` -------------------------------- ### Install @mikro-orm/sql with D1 for pnpm Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install necessary packages for Cloudflare D1 integration using pnpm. ```bash pnpm add @mikro-orm/core @mikro-orm/sql kysely kysely-d1 ``` -------------------------------- ### Install MikroORM PostgreSQL Driver with pnpm Source: https://mikro-orm.io/docs/next/usage-with-cockroachdb Install the core MikroORM package and the PostgreSQL driver using pnpm. ```bash pnpm add @mikro-orm/core @mikro-orm/postgresql ``` -------------------------------- ### Install MikroORM PostgreSQL Driver with Yarn Source: https://mikro-orm.io/docs/next/usage-with-cockroachdb Install the core MikroORM package and the PostgreSQL driver using Yarn. ```bash yarn add @mikro-orm/core @mikro-orm/postgresql ``` -------------------------------- ### Install Mikro-ORM with Cloudflare Durable Objects (Bun) Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install necessary packages for Mikro-ORM with Cloudflare Durable Objects using Bun. ```bash bun add @mikro-orm/core @mikro-orm/sql kysely kysely-durable-objects ``` -------------------------------- ### Initialize project directory structure Source: https://mikro-orm.io/docs/next/guide/first-entity Create the root project folder and the module-specific subdirectories. ```bash # create the project folder and `cd` into it mkdir blog-api && cd blog-api # create module folders, inside `src` folder mkdir -p src/modules/{user,article,common} ``` -------------------------------- ### Install Mikro-ORM with Bun SQLite (bun) Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install necessary packages for Mikro-ORM with Bun's built-in SQLite module. ```bash bun add @mikro-orm/core @mikro-orm/sql kysely kysely-bun-sqlite ``` -------------------------------- ### Install libsql/Turso Driver with Bun Source: https://mikro-orm.io/docs/next/usage-with-sql Install the libsql/Turso driver package for your project using Bun. This package has `@mikro-orm/core` as a peer dependency. ```bash bun add @mikro-orm/libsql ``` -------------------------------- ### Define TPT Entity Hierarchy with defineEntity Source: https://mikro-orm.io/docs/next/inheritance-mapping This example demonstrates defining a multi-level TPT inheritance hierarchy using the `defineEntity` function, starting with a base 'Person' entity. ```typescript const PersonSchema = defineEntity({ name: 'Person', abstract: true, inheritance: 'tpt', properties: { id: p.number().primary(), name: p.string(), }, }); export const Employee = defineEntity({ name: 'Employee', extends: Person, properties: { department: p.string(), }, }); export const Manager = defineEntity({ name: 'Manager', extends: Employee, properties: { teamSize: p.number(), }, }); export class Person extends PersonSchema.class {} PersonSchema.setClass(Person); ``` -------------------------------- ### Define Book Entity with Decorators Source: https://mikro-orm.io/docs/next/quick-start Define a 'Book' entity using decorators, requiring additional setup as detailed in the 'Using Decorators' guide. This approach uses class properties decorated with Mikro-ORM specific annotations. ```typescript import { Collection } from '@mikro-orm/core'; import { Entity, PrimaryKey, Property, ManyToOne, ManyToMany } from '@mikro-orm/decorators/legacy'; @Entity() export class Book { @PrimaryKey() id!: bigint; @Property() title!: string; @ManyToOne(() => Author) author!: Author; @ManyToMany(() => BookTag) tags = new Collection(this); } ``` -------------------------------- ### Install MikroORM with Bun Source: https://mikro-orm.io/docs/next/quick-start Install the core MikroORM package and the specific driver for your database using Bun. Choose the command corresponding to your database. ```bash # for mongodb bun add @mikro-orm/core @mikro-orm/mongodb # for mysql (works with mariadb too) bun add @mikro-orm/core @mikro-orm/mysql # for mariadb (works with mysql too) bun add @mikro-orm/core @mikro-orm/mariadb # for postgresql (works with cockroachdb too) bun add @mikro-orm/core @mikro-orm/postgresql # for sqlite bun add @mikro-orm/core @mikro-orm/sqlite # for libsql/turso bun add @mikro-orm/core @mikro-orm/libsql # for mssql bun add @mikro-orm/core @mikro-orm/mssql # for oracle bun add @mikro-orm/core @mikro-orm/oracledb ``` -------------------------------- ### Install AdminJS Core Source: https://mikro-orm.io/docs/next/usage-with-adminjs Install the core AdminJS package. ```bash $ yarn add adminjs ``` -------------------------------- ### Initialize Bun Project Source: https://mikro-orm.io/docs/next/schema-first-guide Initializes a new Bun project. This creates a package.json file. ```bash bun init ``` -------------------------------- ### Install MikroORM with npm Source: https://mikro-orm.io/docs/next/quick-start Install the core MikroORM package and the specific driver for your database using npm. Choose the command corresponding to your database. ```bash # for mongodb npm install @mikro-orm/core @mikro-orm/mongodb # for mysql (works with mariadb too) npm install @mikro-orm/core @mikro-orm/mysql # for mariadb (works with mysql too) npm install @mikro-orm/core @mikro-orm/mariadb # for postgresql (works with cockroachdb too) npm install @mikro-orm/core @mikro-orm/postgresql # for sqlite npm install @mikro-orm/core @mikro-orm/sqlite # for libsql/turso npm install @mikro-orm/core @mikro-orm/libsql # for mssql npm install @mikro-orm/core @mikro-orm/mssql # for oracle npm install @mikro-orm/core @mikro-orm/oracledb ``` -------------------------------- ### Install Fastify JWT (pnpm) Source: https://mikro-orm.io/docs/next/schema-first-guide Installs the @fastify/jwt package using pnpm. ```bash pnpm add @fastify/jwt ``` -------------------------------- ### Install Fastify JWT (Yarn) Source: https://mikro-orm.io/docs/next/schema-first-guide Installs the @fastify/jwt package using Yarn. ```bash yarn add @fastify/jwt ``` -------------------------------- ### Install Fastify JWT (npm) Source: https://mikro-orm.io/docs/next/schema-first-guide Installs the @fastify/jwt package using npm. ```bash npm install @fastify/jwt ``` -------------------------------- ### Install Vite for Bundling Source: https://mikro-orm.io/docs/next/guide/advanced Installs Vite as a development dependency for bundling the application. ```bash npm install vite --save-dev ``` ```bash yarn add vite --dev ``` ```bash pnpm add vite --save-dev ``` ```bash bun add vite --dev ``` -------------------------------- ### Install pluralize package Source: https://mikro-orm.io/docs/next/schema-first-guide Install the pluralize package and its types for automatic singular/plural transformations. ```bash npm install --save-dev pluralize @types/pluralize ``` ```bash yarn add --dev pluralize @types/pluralize ``` ```bash pnpm add --save-dev pluralize @types/pluralize ``` ```bash bun add --dev pluralize @types/pluralize ``` -------------------------------- ### Install MikroORM with Yarn Source: https://mikro-orm.io/docs/next/quick-start Install the core MikroORM package and the specific driver for your database using Yarn. Choose the command corresponding to your database. ```bash # for mongodb yarn add @mikro-orm/core @mikro-orm/mongodb # for mysql (works with mariadb too) yarn add @mikro-orm/core @mikro-orm/mysql # for mariadb (works with mysql too) yarn add @mikro-orm/core @mikro-orm/mariadb # for postgresql (works with cockroachdb too) yarn add @mikro-orm/core @mikro-orm/postgresql # for sqlite yarn add @mikro-orm/core @mikro-orm/sqlite # for libsql/turso yarn add @mikro-orm/core @mikro-orm/libsql # for mssql yarn add @mikro-orm/core @mikro-orm/mssql # for oracle yarn add @mikro-orm/core @mikro-orm/oracledb ``` -------------------------------- ### Install dataloader dependency Source: https://mikro-orm.io/docs/next/dataloaders Install the dataloader dependency using your preferred package manager. ```bash npm install dataloader ``` ```bash yarn add dataloader ``` ```bash pnpm add dataloader ``` ```bash bun add dataloader ``` -------------------------------- ### Initialize MikroORM with MongoDB Source: https://mikro-orm.io/docs/next/usage-with-mongo Bootstrap the application using the MongoDB driver and clientUrl. ```typescript import { MikroORM } from '@mikro-orm/mongodb'; // or any other driver package const orm = await MikroORM.init({ entities: [Author, Book, ...], dbName: 'my-db-name', clientUrl: '...', }); console.log(orm.em); // access EntityManager via `em` property ``` -------------------------------- ### Bootstrap Fastify App with MikroORM Source: https://mikro-orm.io/docs/next/guide/advanced Initializes the MikroORM, sets up Fastify, registers JWT authentication, and defines global error handlers. This is the main entry point for the application. ```typescript import { NotFoundError, RequestContext } from "@mikro-orm/core"; import { fastify } from "fastify"; import fastifyJWT from "@fastify/jwt"; import { initORM } from "./db.js"; import { registerArticleRoutes } from "./modules/article/routes.js"; import { registerUserRoutes } from "./modules/user/routes.js"; import { AuthError } from "./modules/common/utils.js"; export async function bootstrap(port = 3001, migrate = true) { const db = initORM(); if (migrate) { // sync the schema await db.orm.migrator.up(); } const app = fastify(); // register JWT plugin app.register(fastifyJWT, { secret: process.env.JWT_SECRET ?? "12345678", // fallback for testing }); // register request context hook app.addHook("onRequest", (request, reply, done) => { RequestContext.create(db.em, done); }); // register auth hook after the ORM one to use the context app.addHook("onRequest", async (request) => { try { const ret = await request.jwtVerify<{ id: number }>(); request.user = await db.user.findOneOrFail(ret.id); } catch (e) { app.log.error(e); // ignore token errors, we validate the request.user exists only where needed } }); // register global error handler to process 404 errors from `findOneOrFail` calls app.setErrorHandler((error, request, reply) => { if (error instanceof AuthError) { return reply.status(401).send({ error: error.message }); } if (error instanceof NotFoundError) { return reply.status(404).send({ error: error.message }); } app.log.error(error); reply.status(500).send({ error: error.message }); }); // shut down the connection when closing the app app.addHook("onClose", async () => { await db.orm.close(); }); // register routes here app.register(registerArticleRoutes, { prefix: "article" }); app.register(registerUserRoutes, { prefix: "user" }); const url = await app.listen({ port }); return { app, url, db }; } ``` -------------------------------- ### Bootstrap Fastify Application with ORM Source: https://mikro-orm.io/docs/next/schema-first-guide Sets up a Fastify server, initializes the ORM, applies migrations, and registers request context and shutdown hooks. Includes a basic route for listing articles. ```typescript import { RequestContext } from '@mikro-orm/core'; import { fastify } from 'fastify'; import { initORM } from './db.js'; export async function bootstrap(port = 3001, migrate = true) { const db = initORM({ ensureDatabase: { create: false }, }); if (migrate) { // sync the schema await db.orm.migrator.up(); } const app = fastify(); // register request context hook app.addHook('onRequest', (request, reply, done) => { RequestContext.create(db.em, done); }); // shut down the connection when closing the app app.addHook('onClose', async () => { await db.orm.close(); }); // register routes here app.get('/article', async (request) => { const { limit, offset } = request.query as { limit?: number; offset?: number; }; const [items, total] = await db.article.findAndCount( {}, { limit, offset, } ); return { items, total }; }); const url = await app.listen({ port }); return { app, url }; } ``` -------------------------------- ### Install tinyglobby dependency Source: https://mikro-orm.io/docs/next/upgrading-v6-to-v7 Install tinyglobby to enable brace expansion support for file discovery. ```bash npm install tinyglobby ``` ```bash yarn add tinyglobby ``` ```bash pnpm add tinyglobby ``` ```bash bun add tinyglobby ``` -------------------------------- ### Install MikroORM with pnpm Source: https://mikro-orm.io/docs/next/quick-start Install the core MikroORM package and the specific driver for your database using pnpm. Choose the command corresponding to your database. ```bash # for mongodb pnpm add @mikro-orm/core @mikro-orm/mongodb # for mysql (works with mariadb too) pnpm add @mikro-orm/core @mikro-orm/mysql # for mariadb (works with mysql too) pnpm add @mikro-orm/core @mikro-orm/mariadb # for postgresql (works with cockroachdb too) pnpm add @mikro-orm/core @mikro-orm/postgresql # for sqlite pnpm add @mikro-orm/core @mikro-orm/sqlite # for libsql/turso pnpm add @mikro-orm/core @mikro-orm/libsql # for mssql pnpm add @mikro-orm/core @mikro-orm/mssql # for oracle pnpm add @mikro-orm/core @mikro-orm/oracledb ``` -------------------------------- ### Initialize npm Project Source: https://mikro-orm.io/docs/next/schema-first-guide Initializes a new npm project. This creates a package.json file. ```bash npm init ``` -------------------------------- ### Install Authentication Packages Source: https://mikro-orm.io/docs/next/usage-with-adonis Install the necessary AdonisJS auth and session packages via npm. ```bash npm install @adonisjs/auth @adonisjs/session ``` -------------------------------- ### Fastify App Initialization Source: https://mikro-orm.io/docs/next/schema-first-guide Basic Fastify application setup. Imports necessary modules and initializes the Fastify instance. ```typescript import { fastify } from 'fastify'; ``` -------------------------------- ### Initialize MikroORM with SQL Highlighter Source: https://mikro-orm.io/docs/next/logging Enable SQL query highlighting by initializing MikroORM with an instance of SqlHighlighter. Ensure the '@mikro-orm/sql-highlighter' package is installed. ```typescript import { SqlHighlighter } from '@mikro-orm/sql-highlighter'; MikroORM.init({ highlighter: new SqlHighlighter(), // ... }); ``` -------------------------------- ### Install Mikro-ORM Seeder Package Source: https://mikro-orm.io/docs/next/guide/project-setup Install the seeder package using npm, yarn, pnpm, or bun. ```bash npm install @mikro-orm/seeder ``` ```bash yarn add @mikro-orm/seeder ``` ```bash pnpm add @mikro-orm/seeder ``` ```bash bun add @mikro-orm/seeder ``` -------------------------------- ### Install MikroORM dependencies Source: https://mikro-orm.io/docs/next/usage-with-adonis Install the core MikroORM packages and the desired database driver, along with CLI tools for migrations and seeding. ```bash npm install @mikro-orm/core @mikro-orm/sqlite # or any other driver npm install -D @mikro-orm/cli @mikro-orm/migrations @mikro-orm/seeder ``` -------------------------------- ### MikroORM Initialization for Metadata Discovery Source: https://mikro-orm.io/docs/next/guide/project-setup Demonstrates the basic initialization of MikroORM, emphasizing the importance of the metadata discovery phase for setting up default values and ensuring propagation works correctly, even for unit tests not requiring a database connection. ```typescript const orm = new MikroORM({ // ... }); ``` -------------------------------- ### Install @mikro-orm/sql with D1 for Yarn Source: https://mikro-orm.io/docs/next/usage-with-sqlite Install necessary packages for Cloudflare D1 integration using Yarn. ```bash yarn add @mikro-orm/core @mikro-orm/sql kysely kysely-d1 ``` -------------------------------- ### Initialize MikroORM Source: https://mikro-orm.io/docs/next/quick-start Initialize MikroORM with basic configuration, including entity paths and database name. Ensure you import the correct driver package. ```typescript import { MikroORM } from '@mikro-orm/postgresql'; // or any other driver package const orm = await MikroORM.init({ entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir` dbName: 'my-db-name', }); console.log(orm.em); // access EntityManager via `em` property ``` -------------------------------- ### Debug Mikro-ORM Setup Source: https://mikro-orm.io/docs/next/quick-start Run this command to verify your MIKRO-ORM setup and identify potential configuration issues. ```bash mikro-orm debug ``` -------------------------------- ### Setup MikroORM with Hapi Source: https://mikro-orm.io/docs/next/usage-with-adminjs Initialize MikroORM and register the AdminJS plugin within a Hapi server. ```typescript import AdminJS from 'adminjs'; import { Database, Resource } from '@adminjs/mikroorm'; import AdminJSHapi from '@adminjs/hapi'; import { MikroORM } from '@mikro-orm/postgresql'; import { validate } from 'class-validator'; // optional const PORT = process.env.PORT ?? 3000; const run = async () => { /* Initialize MikroORM like you would do normally, you can also import your MikroORM instance from a separate file */ const orm = await MikroORM.init({ entities: [User, Car, Seller], // use your own entities dbName: process.env.DATABASE_NAME, clientUrl: process.env.DATABASE_URL, }); /* Optional: if you're using class-validator, assign it to Resource */ Resource.validate = validate; /* Tell AdminJS which adapter to use */ AdminJS.registerAdapter({ Database, Resource }); const server = Hapi.server({ port: PORT }) /* Configure AdminJS */ const adminOptions = { databases: [orm], }; /* Register AdminJS as a Hapi server's plugin */ await server.register({ plugin: AdminJSHapi, options: adminOptions, }); await server.start(); console.log(`App listening at ${server.info.uri}`); } run(); ``` -------------------------------- ### Install Renamer for Scripting Source: https://mikro-orm.io/docs/next/schema-first-guide Installs the 'renamer' package as a development dependency. This tool is used to rename files programmatically. ```bash npm install --save-dev renamer ``` ```bash yarn add --dev renamer ``` ```bash pnpm add --save-dev renamer ``` ```bash bun add --dev renamer ``` -------------------------------- ### Install Zod for Validation Source: https://mikro-orm.io/docs/next/guide/advanced Installs the Zod library, a popular schema declaration and validation library for TypeScript and JavaScript. ```bash npm install zod ``` ```bash yarn add zod ``` ```bash pnpm add zod ``` ```bash bun add zod ``` -------------------------------- ### Install Core and Driver Packages with Bun Source: https://mikro-orm.io/docs/next/usage-with-sql Explicitly install `@mikro-orm/core` along with your chosen driver and other packages like CLI or migrations when using Bun. This ensures all packages share the same instance. ```bash bun add @mikro-orm/core @mikro-orm/postgresql @mikro-orm/migrations @mikro-orm/cli ``` -------------------------------- ### Create Project Directory Source: https://mikro-orm.io/docs/next/schema-first-guide Use this command to create a new directory for your project and navigate into it. ```bash mkdir blog-api && cd blog-api ``` -------------------------------- ### Create Entity Instances with em.create() Source: https://mikro-orm.io/docs/next/usage-with-js Demonstrates creating entity instances for Author and Book using the entity manager's create method, followed by flushing changes to the database. ```javascript const author = em.create(Author, { name: 'Jon Snow', email: 'jon@wall.st', }); const book = em.create(Book, { title: 'My Life on the Wall', author, }); await em.flush(); ``` -------------------------------- ### Example Mikro-ORM Migrations Configuration Source: https://mikro-orm.io/docs/next/migrations This example demonstrates a customized Mikro-ORM migrations configuration. It specifies custom paths, a different glob pattern, and disables table dropping for safety. ```typescript await MikroORM.init({ migrations: { tableName: 'my_migrations', path: 'dist/migrations', pathTs: 'src/migrations', glob: '*.{js,ts}', silent: false, transactional: true, disableForeignKeys: true, allOrNothing: true, dropTables: false, // disable table dropping for safety safe: false, snapshot: true, emit: 'ts', fileName: (timestamp, name) => `${timestamp}_${name || 'migration'}`, }, }); ``` -------------------------------- ### Initialize pnpm Project Source: https://mikro-orm.io/docs/next/schema-first-guide Initializes a new pnpm project. This creates a package.json file. ```bash pnpm init ``` -------------------------------- ### TPT Operation Examples Source: https://mikro-orm.io/docs/next/inheritance-mapping Examples demonstrating how MikroORM handles INSERT, UPDATE, and DELETE operations for TPT inheritance. ```typescript const employee = em.create(Employee, { name: 'John Doe', department: 'Engineering', }); await em.flush(); // Executes: // INSERT INTO person (name) VALUES ('John Doe') -- returns id=1 // INSERT INTO employee (id, department) VALUES (1, 'Engineering') ``` ```typescript employee.department = 'Sales'; // Only updates employee table employee.name = 'Jane Doe'; // Only updates person table await em.flush(); ``` ```typescript em.remove(employee); await em.flush(); // Executes: // DELETE FROM person WHERE id = 1 // (employee row is deleted automatically via ON DELETE CASCADE) ``` -------------------------------- ### Initialize MikroORM and Create User Source: https://mikro-orm.io/docs/next/guide/first-entity This example demonstrates initializing MikroORM with SQLite configuration and creating a new user entity. It highlights that `em.create()` auto-persists the entity, requiring only `em.flush()` to save it. After flushing, the entity becomes managed and its ID is available. ```typescript import { MikroORM } from '@mikro-orm/sqlite'; import config from './mikro-orm.config.js'; import { UserSchema } from './modules/user/user.entity.js'; const orm = await MikroORM.init(config); // create new user entity instance via em.create() const user = orm.em.create(UserSchema, { email: 'foo@bar.com', fullName: 'Foo Bar', password: '123456', }); // em.create() auto-persists, so just flush await orm.em.flush(); // after the entity is flushed, it becomes managed, and has the PK available console.log('user id is:', user.id); ``` -------------------------------- ### Install Zod with pnpm Source: https://mikro-orm.io/docs/next/schema-first-guide Install the Zod library using pnpm. This is another package manager option for integrating Zod. ```bash pnpm add zod ``` -------------------------------- ### Install Zod with Yarn Source: https://mikro-orm.io/docs/next/schema-first-guide Install the Zod library using Yarn. This is an alternative package manager for adding Zod to your project. ```bash yarn add zod ```