- Notifications
You must be signed in to change notification settings - Fork571
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.
License
mikro-orm/mikro-orm
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
TypeScript ORM for Node.js based on Data Mapper,Unit of Work andIdentity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite (including libSQL) databases.
You might be asking:What the hell is Unit of Work and why should I care about it?
Unit of Work maintains a list of objects (entities) affected by a business transactionand coordinates the writing out of changes.(Martin Fowler)
Identity Map ensures that each object (entity) gets loaded only once by keeping everyloaded object in a map. Looks up objects using the map when referring to them.(Martin Fowler)
So what benefits does it bring to us?
First and most important implication of having Unit of Work is that it allows handling transactions automatically.
When you callem.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 callingem.persistLater()
and once all your changes are ready, callingflush()
will run them inside a transaction.
You can also control the transaction boundaries manually via
em.transactional(cb)
.
constuser=awaitem.findOneOrFail(User,1);user.email='foo@bar.com';constcar=newCar();user.cars.add(car);// thanks to bi-directional cascading we only need to persist user entity// flushing will create a transaction, insert new car and update user with new email// as user entity is managed, calling flush() is enoughawaitem.flush();
MikroORM 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 theUser
entity used in previous example:
@Entity()exportclassUser{ @PrimaryKey()id!:number; @Property()name!:string; @OneToOne(()=>Address)address?:Address; @ManyToMany(()=>Car)cars=newCollection<Car>(this);constructor(name:string){this.name=name;}}
Now to create new instance of theUser
entity, we are forced to provide thename
:
constuser=newUser('John Doe');// name is required to create new user instanceuser.address=newAddress('10 Downing Street');// address is optional
Once your entities are loaded, make a number of synchronous actions on your entities,then callem.flush()
. This will trigger computing of change sets. Only entities(and properties) that were changed will generate database queries, if there are no changes,no transaction will be started.
constuser=awaitem.findOneOrFail(User,1,{populate:['cars','address.city'],});user.title='Mr.';user.address.street='10 Downing Street';// address is 1:1 relation of Address entityuser.cars.getItems().forEach(car=>car.forSale=true);// cars is 1:m collection of Car entitiesconstcar=newCar('VW');user.cars.add(car);// now we can flush all changes done to managed entitiesawaitem.flush();
em.flush()
will then execute these queries from the example above:
begin;update"user"set"title"='Mr.'where"id"=1;update"user_address"set"street"='10 Downing Street'where"id"=123;update"car"set"for_sale"= case when ("id"=1) then true when ("id"=2) then true when ("id"=3) then true else"for_sale" endwhere"id"in (1,2,3)insert into"car" ("brand","owner")values ('VW',1);commit;
Thanks 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
).
MikroORM documentation, included in this repo in the root directory, is built withDocusaurus and publicly hosted on GitHub Pages athttps://mikro-orm.io.
There is also auto-generatedCHANGELOG.md file based on commit messages (viasemantic-release
).
- Clean and Simple Entity Definition
- Identity Map
- Entity References
- Using Entity Constructors
- Modelling Relationships
- Collections
- Unit of Work
- Transactions
- Cascading persist and remove
- Composite and Foreign Keys as Primary Key
- Filters
- Using
QueryBuilder
- Preloading Deeply Nested Structures via populate
- Property Validation
- Lifecycle Hooks
- Vanilla JS Support
- Schema Generator
- Entity Generator
You can find example integrations for some popular frameworks in themikro-orm-examples
repository:
- Express + MongoDB
- Nest + MySQL
- RealWorld example app (Nest + MySQL)
- Koa + SQLite
- GraphQL + PostgreSQL
- Inversify + PostgreSQL
- NextJS + MySQL
- Accounts.js REST and GraphQL authentication + SQLite
- Nest + Shopify + PostgreSQL + GraphQL
- Elysia.js + libSQL + Bun
- Electron.js + PostgreSQL
First install the module viayarn
ornpm
and do not forget to install the database driver as well:
Since v4, you should install the driver package, but not the db connector itself, e.g. install
@mikro-orm/sqlite
, but notsqlite3
as that is already included in the driver package.
yarn add @mikro-orm/core @mikro-orm/mongodb# for mongoyarn add @mikro-orm/core @mikro-orm/mysql# for mysql/mariadbyarn add @mikro-orm/core @mikro-orm/mariadb# for mysql/mariadbyarn add @mikro-orm/core @mikro-orm/postgresql# for postgresqlyarn add @mikro-orm/core @mikro-orm/mssql# for mssqlyarn add @mikro-orm/core @mikro-orm/sqlite# for sqliteyarn add @mikro-orm/core @mikro-orm/better-sqlite# for better-sqliteyarn add @mikro-orm/core @mikro-orm/libsql# for libsql
or
npm i -s @mikro-orm/core @mikro-orm/mongodb# for mongonpm i -s @mikro-orm/core @mikro-orm/mysql# for mysql/mariadbnpm i -s @mikro-orm/core @mikro-orm/mariadb# for mysql/mariadbnpm i -s @mikro-orm/core @mikro-orm/postgresql# for postgresqlnpm i -s @mikro-orm/core @mikro-orm/mssql# for mssqlnpm i -s @mikro-orm/core @mikro-orm/sqlite# for sqlitenpm i -s @mikro-orm/core @mikro-orm/better-sqlite# for better-sqlitenpm i -s @mikro-orm/core @mikro-orm/libsql# for libsql
Next, if you want to use decorators for your entity definition, you will need to enable support fordecorators as well asesModuleInterop
intsconfig.json
via:
"experimentalDecorators":true,"emitDecoratorMetadata":true,"esModuleInterop":true,
Alternatively, you can useEntitySchema
.
Then callMikroORM.init
as part of bootstrapping your app:
To access driver specific methods like
em.createQueryBuilder()
we need to specify the driver type when callingMikroORM.init()
. Alternatively we can cast theorm.em
toEntityManager
exported from the driver package:import{EntityManager}from'@mikro-orm/postgresql';constem=orm.emasEntityManager;constqb=em.createQueryBuilder(...);
importtype{PostgreSqlDriver}from'@mikro-orm/postgresql';// or any other SQL driver packageconstorm=awaitMikroORM.init<PostgreSqlDriver>({entities:['./dist/entities'],// path to your JS entities (dist), relative to `baseDir`dbName:'my-db-name',type:'postgresql',});console.log(orm.em);// access EntityManager via `em` property
There are more ways to configure your entities, take a look atinstallation page.
Read more about all the possible configuration options inAdvanced Configuration section.
Then you will need to fork entity manager for each request so theiridentity maps will not collide. To do so, use theRequestContext
helper:
constapp=express();app.use((req,res,next)=>{RequestContext.create(orm.em,next);});
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
orbodyParser
, so definitely register the context after them.
More info aboutRequestContext
is describedhere.
Now you can start defining your entities (in one of theentities
folders). This is how simple entity can look like in mongo driver:
./entities/MongoBook.ts
@Entity()exportclassMongoBook{ @PrimaryKey()_id:ObjectID; @SerializedPrimaryKey()id:string; @Property()title:string; @ManyToOne(()=>Author)author:Author; @ManyToMany(()=>BookTag)tags=newCollection<BookTag>(this);constructor(title:string,author:Author){this.title=title;this.author=author;}}
For SQL drivers, you can useid: number
PK:
./entities/SqlBook.ts
@Entity()exportclassSqlBook{ @PrimaryKey()id:number;}
Or if you want to use UUID primary keys:
./entities/UuidBook.ts
import{randomUUID}from'node:crypto';@Entity()exportclassUuidBook{ @PrimaryKey()uuid=randomUUID();}
More information can be found indefining entities section in docs.
When you have your entities defined, you can start using ORM either viaEntityManager
or viaEntityRepository
s.
To save entity state to database, you need to persist it. Persist takes care or deciding whether to useinsert
orupdate
and computes appropriate change-set. Entity references that are not persisted yet (does not have identifier) will be cascade persisted automatically.
// use constructors in your entities for required parametersconstauthor=newAuthor('Jon Snow','snow@wall.st');author.born=newDate();constpublisher=newPublisher('7K publisher');constbook1=newBook('My Life on The Wall, part 1',author);book1.publisher=publisher;constbook2=newBook('My Life on The Wall, part 2',author);book2.publisher=publisher;constbook3=newBook('My Life on The Wall, part 3',author);book3.publisher=publisher;// just persist books, author and publisher will be automatically cascade persistedawaitem.persistAndFlush([book1,book2,book3]);
To fetch entities from database you can usefind()
andfindOne()
ofEntityManager
:
constauthors=em.find(Author,{},{populate:['books']});for(constauthorofauthors){console.log(author);// instance of Author entityconsole.log(author.name);// Jon Snowfor(constbookofauthor.books){// iterating books collectionconsole.log(book);// instance of Book entityconsole.log(book.title);// My Life on The Wall, part 1/2/3}}
More convenient way of fetching entities from database is by usingEntityRepository
, that carries the entity name, so you do not have to pass it to everyfind
andfindOne
calls:
constbooksRepository=em.getRepository(Book);constbooks=awaitbooksRepository.find({author:'...'},{populate:['author'],limit:1,offset:2,orderBy:{title:QueryOrder.DESC},});console.log(books);// Loaded<Book, 'author'>[]
Take a look at docs aboutworking withEntityManager
orusingEntityRepository
instead.
Contributions, issues and feature requests are welcome. Please readCONTRIBUTING.md for details on the process for submitting pull requests to us.
👤Martin Adámek
See also the list of contributors whoparticipated in this project.
Please ⭐️ this repository if this project helped you!
Copyright © 2018Martin Adámek.
This project is licensed under the MIT License - see theLICENSE file for details.
About
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.