{"id":13454835,"url":"https://github.com/mikro-orm/mikro-orm","last_synced_at":"2026-02-15T22:05:33.703Z","repository":{"id":37412091,"uuid":"125342064","full_name":"mikro-orm/mikro-orm","owner":"mikro-orm","description":"TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, MS SQL Server, PostgreSQL and SQLite/libSQL databases.","archived":false,"fork":false,"pushed_at":"2025-05-05T07:04:10.000Z","size":70710,"stargazers_count":8241,"open_issues_count":59,"forks_count":568,"subscribers_count":48,"default_branch":"master","last_synced_at":"2025-05-05T14:53:55.249Z","etag":null,"topics":["database","datamapper","entities","entity","identity-map","javascript","libsql","mongodb","mysql","nodejs","orm","postgre","postgresql","sql","sql-server","sqlite","sqlite3","typescript","typescript-orm","unit-of-work"],"latest_commit_sha":null,"homepage":"https://mikro-orm.io","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mikro-orm.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["B4nan"],"custom":"https://paypal.me/mikroorm"}},"created_at":"2018-03-15T09:21:10.000Z","updated_at":"2025-05-05T14:27:16.000Z","dependencies_parsed_at":"2023-10-24T00:30:14.406Z","dependency_job_id":"b2315177-6023-46e2-b406-7ddfd02128a9","html_url":"https://github.com/mikro-orm/mikro-orm","commit_stats":{"total_commits":5512,"total_committers":269,"mean_commits":"20.490706319702603","dds":0.3791727140783745,"last_synced_commit":"a3b5e5704918a44c4d30b1c5a007b9cc648f6130"},"previous_names":[],"tags_count":302,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikro-orm%2Fmikro-orm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikro-orm%2Fmikro-orm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikro-orm%2Fmikro-orm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikro-orm%2Fmikro-orm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mikro-orm","download_url":"https://codeload.github.com/mikro-orm/mikro-orm/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253777006,"owners_count":21962609,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","datamapper","entities","entity","identity-map","javascript","libsql","mongodb","mysql","nodejs","orm","postgre","postgresql","sql","sql-server","sqlite","sqlite3","typescript","typescript-orm","unit-of-work"],"created_at":"2024-07-31T08:00:58.369Z","updated_at":"2026-01-22T00:17:55.382Z","avatar_url":"https://github.com/mikro-orm.png","language":"TypeScript","readme":"\u003ch1 align=\"center\"\u003e\n  \u003ca href=\"https://mikro-orm.io\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/mikro-orm/mikro-orm/master/docs/static/img/logo-readme.svg?sanitize=true\" alt=\"MikroORM\" /\u003e\u003c/a\u003e\n\u003c/h1\u003e\n\nTypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite (including libSQL) databases. \n\n\u003e Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Hibernate](https://hibernate.org/).\n\n[![NPM version](https://img.shields.io/npm/v/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)\n[![NPM dev version](https://img.shields.io/npm/v/@mikro-orm/core/next.svg)](https://www.npmjs.com/package/@mikro-orm/core)\n[![Chat on discord](https://img.shields.io/discord/1214904142443839538?label=discord\u0026color=blue)](https://discord.gg/w8bjxFHS7X)\n[![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)\n[![Coverage Status](https://img.shields.io/coveralls/mikro-orm/mikro-orm.svg)](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)\n[![Build Status](https://github.com/mikro-orm/mikro-orm/workflows/tests/badge.svg?branch=master)](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)\n\n## 🤔 Unit of What?\n\nYou might be asking: _What the hell is Unit of Work and why should I care about it?_\n\n\u003e Unit of Work maintains a list of objects (_entities_) affected by a business transaction \n\u003e and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)\n\n\u003e Identity Map ensures that each object (_entity_) gets loaded only once by keeping every \n\u003e loaded object in a map. Looks up objects using the map when referring to them. \n\u003e [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/identityMap.html)\n\nSo what benefits does it bring to us?\n\n### Implicit Transactions\n\nFirst and most important implication of having Unit of Work is that it allows handling transactions automatically. \n\nWhen you call `em.flush()`, all computed changes are queried inside a database transaction (if supported by given driver). This means that you can control the boundaries of transactions simply by calling `em.persistLater()` and once all your changes are ready, calling `flush()` will run them inside a transaction. \n\n\u003e You can also control the transaction boundaries manually via `em.transactional(cb)`.\n\n```typescript\nconst user = await em.findOneOrFail(User, 1);\nuser.email = 'foo@bar.com';\nconst car = new Car();\nuser.cars.add(car);\n\n// thanks to bi-directional cascading we only need to persist user entity\n// flushing will create a transaction, insert new car and update user with new email\n// as user entity is managed, calling flush() is enough\nawait em.flush();\n```\n\n### ChangeSet based persistence\n\nMikroORM allows you to implement your domain/business logic directly in the entities. To maintain always valid entities, you can use constructors to mark required properties. Let's define the `User` entity used in previous example:\n\n```typescript\n@Entity()\nexport class User {\n\n  @PrimaryKey()\n  id!: number;\n\n  @Property()\n  name!: string;\n\n  @OneToOne(() =\u003e Address)\n  address?: Address;\n\n  @ManyToMany(() =\u003e Car)\n  cars = new Collection\u003cCar\u003e(this);\n\n  constructor(name: string) {\n    this.name = name;\n  }\n\n}\n```\n\nNow to create new instance of the `User` entity, we are forced to provide the `name`:\n\n```typescript\nconst user = new User('John Doe'); // name is required to create new user instance\nuser.address = new Address('10 Downing Street'); // address is optional\n```\n\nOnce your entities are loaded, make a number of synchronous actions on your entities,\nthen call `em.flush()`. This will trigger computing of change sets. Only entities \n(and properties) that were changed will generate database queries, if there are no changes, \nno transaction will be started.\n\n```typescript\nconst user = await em.findOneOrFail(User, 1, {\n  populate: ['cars', 'address.city'],\n});\nuser.title = 'Mr.';\nuser.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity\nuser.cars.getItems().forEach(car =\u003e car.forSale = true); // cars is 1:m collection of Car entities\nconst car = new Car('VW');\nuser.cars.add(car);\n\n// now we can flush all changes done to managed entities\nawait em.flush();\n```\n\n`em.flush()` will then execute these queries from the example above:\n\n```sql\nbegin;\nupdate \"user\" set \"title\" = 'Mr.' where \"id\" = 1;\nupdate \"user_address\" set \"street\" = '10 Downing Street' where \"id\" = 123;\nupdate \"car\"\n  set \"for_sale\" = case\n    when (\"id\" = 1) then true\n    when (\"id\" = 2) then true\n    when (\"id\" = 3) then true\n    else \"for_sale\" end\n  where \"id\" in (1, 2, 3)\ninsert into \"car\" (\"brand\", \"owner\") values ('VW', 1);\ncommit;\n```\n\n### Identity Map\n\nThanks to Identity Map, you will always have only one instance of given entity in one context. This allows for some optimizations (skipping loading of already loaded entities), as well as comparison by identity (`ent1 === ent2`). \n\n## 📖 Documentation\n\nMikroORM documentation, included in this repo in the root directory, is built with [Docusaurus](https://docusaurus.io) and publicly hosted on GitHub Pages at https://mikro-orm.io.\n\nThere is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`). \n\n## ✨ Core Features\n\n- [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities)\n- [Identity Map](https://mikro-orm.io/docs/identity-map)\n- [Entity References](https://mikro-orm.io/docs/entity-references)\n- [Using Entity Constructors](https://mikro-orm.io/docs/entity-constructors)\n- [Modelling Relationships](https://mikro-orm.io/docs/relationships)\n- [Collections](https://mikro-orm.io/docs/collections)\n- [Unit of Work](https://mikro-orm.io/docs/unit-of-work)\n- [Transactions](https://mikro-orm.io/docs/transactions)\n- [Cascading persist and remove](https://mikro-orm.io/docs/cascading)\n- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)\n- [Filters](https://mikro-orm.io/docs/filters)\n- [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)\n- [Populating relations](https://mikro-orm.io/docs/populating-relations)\n- [Property Validation](https://mikro-orm.io/docs/property-validation)\n- [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)\n- [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)\n- [Schema Generator](https://mikro-orm.io/docs/schema-generator)\n- [Entity Generator](https://mikro-orm.io/docs/entity-generator)\n\n## 📦 Example Integrations\n\nYou can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples): \n\n### TypeScript Examples\n\n- [Express + MongoDB](https://github.com/mikro-orm/express-ts-example-app)\n- [Nest + MySQL](https://github.com/mikro-orm/nestjs-example-app)\n- [RealWorld example app (Nest + MySQL)](https://github.com/mikro-orm/nestjs-realworld-example-app)\n- [Koa + SQLite](https://github.com/mikro-orm/koa-ts-example-app)\n- [GraphQL + PostgreSQL](https://github.com/driescroons/mikro-orm-graphql-example)\n- [Inversify + PostgreSQL](https://github.com/PodaruDragos/inversify-example-app)\n- [NextJS + MySQL](https://github.com/jonahallibone/mikro-orm-nextjs)\n- [Accounts.js REST and GraphQL authentication + SQLite](https://github.com/darkbasic/mikro-orm-accounts-example)\n- [Nest + Shopify + PostgreSQL + GraphQL](https://github.com/Cloudshelf/Shopify_CSConnector)\n- [Elysia.js + libSQL + Bun](https://github.com/mikro-orm/elysia-bun-example-app)\n- [Electron.js + PostgreSQL](https://github.com/adnanlah/electron-mikro-orm-example-app)\n\n### JavaScript Examples \n\n- [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)\n\n## 🚀 Quick Start\n\nFirst install the module via `yarn` or `npm` and do not forget to install the database driver as well:\n\n\u003e Since v4, you should install the driver package, but not the db connector itself, e.g. install `@mikro-orm/sqlite`, but not `sqlite3` as that is already included in the driver package.\n\n```sh\nyarn add @mikro-orm/core @mikro-orm/mongodb       # for mongo\nyarn add @mikro-orm/core @mikro-orm/mysql         # for mysql/mariadb\nyarn add @mikro-orm/core @mikro-orm/mariadb       # for mysql/mariadb\nyarn add @mikro-orm/core @mikro-orm/postgresql    # for postgresql\nyarn add @mikro-orm/core @mikro-orm/mssql         # for mssql\nyarn add @mikro-orm/core @mikro-orm/sqlite        # for sqlite\nyarn add @mikro-orm/core @mikro-orm/libsql        # for libsql\n```\n\nor\n\n```sh\nnpm i -s @mikro-orm/core @mikro-orm/mongodb       # for mongo\nnpm i -s @mikro-orm/core @mikro-orm/mysql         # for mysql/mariadb\nnpm i -s @mikro-orm/core @mikro-orm/mariadb       # for mysql/mariadb\nnpm i -s @mikro-orm/core @mikro-orm/postgresql    # for postgresql\nnpm i -s @mikro-orm/core @mikro-orm/mssql         # for mssql\nnpm i -s @mikro-orm/core @mikro-orm/sqlite        # for sqlite\nnpm i -s @mikro-orm/core @mikro-orm/libsql        # for libsql\n```\n\nNext, if you want to use decorators for your entity definition, you will need to enable support for [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) as well as `esModuleInterop` in `tsconfig.json` via:\n\n```json\n\"experimentalDecorators\": true,\n\"emitDecoratorMetadata\": true,\n\"esModuleInterop\": true,\n```\n\nAlternatively, you can use [`EntitySchema`](https://mikro-orm.io/docs/entity-schema).\n\nThen call `MikroORM.init` as part of bootstrapping your app:\n\n\u003e To access driver specific methods like `em.createQueryBuilder()` we need to specify the driver type when calling `MikroORM.init()`. Alternatively we can cast the `orm.em` to `EntityManager` exported from the driver package:\n\u003e \n\u003e ```ts\n\u003e import { EntityManager } from '@mikro-orm/postgresql';\n\u003e const em = orm.em as EntityManager;\n\u003e const qb = em.createQueryBuilder(...);\n\u003e ```\n\n```typescript\nimport type { PostgreSqlDriver } from '@mikro-orm/postgresql'; // or any other SQL driver package\n\nconst orm = await MikroORM.init\u003cPostgreSqlDriver\u003e({\n  entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir`\n  dbName: 'my-db-name',\n  type: 'postgresql',\n});\nconsole.log(orm.em); // access EntityManager via `em` property\n```\n\nThere are more ways to configure your entities, take a look at [installation page](https://mikro-orm.io/docs/installation/).\n\n\u003e Read more about all the possible configuration options in [Advanced Configuration](https://mikro-orm.io/docs/configuration) section.\n\nThen you will need to fork entity manager for each request so their [identity maps](https://mikro-orm.io/docs/identity-map/) will not collide. To do so, use the `RequestContext` helper:\n\n```typescript\nconst app = express();\n\napp.use((req, res, next) =\u003e {\n  RequestContext.create(orm.em, next);\n});\n```\n\n\u003e You should register this middleware as the last one just before request handlers and before any of your custom middleware that is using the ORM. There might be issues when you register it before request processing middleware like `queryParser` or `bodyParser`, so definitely register the context after them. \n\nMore info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).\n\nNow you can start defining your entities (in one of the `entities` folders). This is how simple entity can look like in mongo driver:\n\n**`./entities/MongoBook.ts`**\n\n```typescript\n@Entity()\nexport class MongoBook {\n\n  @PrimaryKey()\n  _id: ObjectID;\n\n  @SerializedPrimaryKey()\n  id: string;\n\n  @Property()\n  title: string;\n\n  @ManyToOne(() =\u003e Author)\n  author: Author;\n\n  @ManyToMany(() =\u003e BookTag)\n  tags = new Collection\u003cBookTag\u003e(this);\n\n  constructor(title: string, author: Author) {\n    this.title = title;\n    this.author = author;\n  }\n\n}\n```\n\nFor SQL drivers, you can use `id: number` PK:\n\n**`./entities/SqlBook.ts`**\n\n```typescript\n@Entity()\nexport class SqlBook {\n\n  @PrimaryKey()\n  id: number;\n\n}\n```\n\nOr if you want to use UUID primary keys:\n\n**`./entities/UuidBook.ts`**\n\n```typescript\nimport { randomUUID } from 'node:crypto';\n\n@Entity()\nexport class UuidBook {\n\n  @PrimaryKey()\n  uuid = randomUUID();\n\n}\n```\n\nMore information can be found in [defining entities section](https://mikro-orm.io/docs/defining-entities/) in docs.\n\nWhen you have your entities defined, you can start using ORM either via `EntityManager` or via `EntityRepository`s.\n\nTo save entity state to database, you need to persist it. Persist takes care or deciding whether to use `insert` or `update` and computes appropriate change-set. Entity references that are not persisted yet (does not have identifier) will be cascade persisted automatically. \n\n```typescript\n// use constructors in your entities for required parameters\nconst author = new Author('Jon Snow', 'snow@wall.st');\nauthor.born = new Date();\n\nconst publisher = new Publisher('7K publisher');\n\nconst book1 = new Book('My Life on The Wall, part 1', author);\nbook1.publisher = publisher;\nconst book2 = new Book('My Life on The Wall, part 2', author);\nbook2.publisher = publisher;\nconst book3 = new Book('My Life on The Wall, part 3', author);\nbook3.publisher = publisher;\n\n// just persist books, author and publisher will be automatically cascade persisted\nawait em.persistAndFlush([book1, book2, book3]);\n```\n\nTo fetch entities from database you can use `find()` and `findOne()` of `EntityManager`: \n\n```typescript\nconst authors = em.find(Author, {}, { populate: ['books'] });\n\nfor (const author of authors) {\n  console.log(author); // instance of Author entity\n  console.log(author.name); // Jon Snow\n\n  for (const book of author.books) { // iterating books collection\n    console.log(book); // instance of Book entity\n    console.log(book.title); // My Life on The Wall, part 1/2/3\n  }\n}\n```\n\nMore convenient way of fetching entities from database is by using `EntityRepository`, that carries the entity name, so you do not have to pass it to every `find` and `findOne` calls:\n\n```typescript\nconst booksRepository = em.getRepository(Book);\n\nconst books = await booksRepository.find({ author: '...' }, { \n  populate: ['author'],\n  limit: 1,\n  offset: 2,\n  orderBy: { title: QueryOrder.DESC },\n});\n\nconsole.log(books); // Loaded\u003cBook, 'author'\u003e[]\n```\n\nTake a look at docs about [working with `EntityManager`](https://mikro-orm.io/docs/entity-manager/) or [using `EntityRepository` instead](https://mikro-orm.io/docs/repositories/).\n\n## 🤝 Contributing\n\nContributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.\n\n## Authors\n\n👤 **Martin Adámek**\n\n- Twitter: [@B4nan](https://twitter.com/B4nan)\n- Github: [@b4nan](https://github.com/b4nan)\n\nSee also the list of contributors who [participated](https://github.com/mikro-orm/mikro-orm/contributors) in this project.\n\n## Show Your Support\n\nPlease ⭐️ this repository if this project helped you!\n\n\u003e If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).\n\n## 📝 License\n\nCopyright © 2018 [Martin Adámek](https://github.com/b4nan).\n\nThis project is licensed under the MIT License - see the [LICENSE file](LICENSE) for details.\n","funding_links":["https://github.com/sponsors/B4nan","https://paypal.me/mikroorm","https://github.com/sponsors/b4nan"],"categories":["Packages","TypeScript","Projects using `@faker-js/faker`","Repository","包","目录","其他__大数据","ORM","Recently Updated","typescript","Built with TypeScript","Uncategorized","\u003ca name=\"TypeScript\"\u003e\u003c/a\u003eTypeScript"],"sub_categories":["Database","数据库","网络服务_其他","Other","[Feb 17, 2025](/content/2025/02/17/README.md)","Libraries","Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmikro-orm%2Fmikro-orm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmikro-orm%2Fmikro-orm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmikro-orm%2Fmikro-orm/lists"}