MikroORM

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity ...

README

MikroORM


TypeScript ORM for Node.js based on Data Mapper, Unit of Work
and Identity Map patterns. Supports MongoDB, MySQL,
MariaDB, PostgreSQL and SQLite databases.

Heavily inspired by Doctrine and Nextras Orm.

NPM version NPM dev version Chat on slack Downloads Coverage Status Maintainability Build Status

🤔 Unit of What?


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 transaction

and coordinates the writing out of changes. (Martin Fowler)


Identity Map ensures that each object (_entity_) gets loaded only once by keeping every

loaded object in a map. Looks up objects using the map when referring to them.


So what benefits does it bring to us?

Implicit Transactions


First and most important implication of having Unit of Work is that it allows handling
transactions automatically.

When 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.

You can also control the transaction boundaries manually via em.transactional(cb).


  1. ```typescript
  2. const user = await em.findOneOrFail(User, 1);
  3. user.email = 'foo@bar.com';
  4. const car = new Car();
  5. user.cars.add(car);

  6. // thanks to bi-directional cascading we only need to persist user entity
  7. // flushing will create a transaction, insert new car and update user with new email
  8. // as user entity is managed, calling flush() is enough
  9. await em.flush();
  10. ```

ChangeSet based persistence


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 the User entity used in previous example:

  1. ```typescript
  2. @Entity()
  3. export class User {

  4.   @PrimaryKey()
  5.   id!: number;

  6.   @Property()
  7.   name!: string;

  8.   @OneToOne()
  9.   address?: Address;

  10.   @ManyToMany()
  11.   cars = new Collection<Car>(this);

  12.   constructor(name: string) {
  13.     this.name = name;
  14.   }

  15. }
  16. ```

Now to create new instance of the User entity, we are forced to provide the name:

  1. ```typescript
  2. const user = new User('John Doe'); // name is required to create new user instance
  3. user.address = new Address('10 Downing Street'); // address is optional
  4. ```

Once your entities are loaded, make a number of synchronous actions on your entities,
then call em.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.

  1. ```typescript
  2. const user = await em.findOneOrFail(User, 1, ['cars', 'address']);
  3. user.title = 'Mr.';
  4. user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity
  5. user.cars.getItems().forEach(car => car.forSale = true); // cars is 1:m collection of Car entities
  6. const car = new Car('VW');
  7. user.cars.add(car);

  8. // now we can flush all changes done to managed entities
  9. await em.flush();
  10. ```

em.flush() will then execute these queries from the example above:

  1. ```sql
  2. begin;
  3. update user set title = 'Mr.' where id = 1;
  4. update user_address set street = '10 Downing Street' where id = 123;
  5. update car set for_sale = true where id = 1;
  6. update car set for_sale = true where id = 2;
  7. update car set for_sale = true where id = 3;
  8. insert into car (brand, owner) values ('VW', 1);
  9. commit;
  10. ```

Only One Instance of Entity


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).

📖 Documentation


MikroORM v4 documentation, included in this repo in the root directory, is built with
Jekyll and publicly hosted on GitHub Pages at https://mikro-orm.io.

There is also auto-generated CHANGELOG.md file based on commit messages
(via semantic-release).

You can browse MikroORM v3 docs at https://mikro-orm.io/docs/3.6/installation.


To upgrade to v4, please see the upgrading guide.


✨ Core Features


- [Using QueryBuilder](https://mikro-orm.io/docs/query-builder/)

📦 Example Integrations


You can find example integrations for some popular frameworks in the [mikro-orm-examples repository](https://github.com/mikro-orm/mikro-orm-examples):

TypeScript Examples



JavaScript Examples


Articles


- Introducing MikroORM, TypeScript data-mapper ORM with Identity Map
  - on medium.com
  - on dev.to
- Handling transactions and concurrency in MikroORM
  - on medium.com
  - on dev.to
- MikroORM 3: Knex.js, CLI, Schema Updates, Entity Generator and more…
  - on medium.com
  - on dev.to

🚀 Quick Start


First install the module via yarn or npm 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 not sqlite3 as that is already included

in the driver package.


  1. ```sh
  2. yarn add @mikro-orm/core @mikro-orm/mongodb     # for mongo
  3. yarn add @mikro-orm/core @mikro-orm/mysql       # for mysql/mariadb
  4. yarn add @mikro-orm/core @mikro-orm/mariadb     # for mysql/mariadb
  5. yarn add @mikro-orm/core @mikro-orm/postgresql  # for postgresql
  6. yarn add @mikro-orm/core @mikro-orm/sqlite      # for sqlite
  7. ```

or

  1. ```sh
  2. npm i -s @mikro-orm/core @mikro-orm/mongodb     # for mongo
  3. npm i -s @mikro-orm/core @mikro-orm/mysql       # for mysql/mariadb
  4. npm i -s @mikro-orm/core @mikro-orm/mariadb     # for mysql/mariadb
  5. npm i -s @mikro-orm/core @mikro-orm/postgresql  # for postgresql
  6. npm i -s @mikro-orm/core @mikro-orm/sqlite      # for sqlite
  7. ```

Next you will need to enable support for decorators
as well as esModuleInterop in tsconfig.json via:

  1. ``` json
  2. "experimentalDecorators": true,
  3. "emitDecoratorMetadata": true,
  4. "esModuleInterop": true,
  5. ```

Then call MikroORM.init as part of bootstrapping your app:

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:

>ts

import { EntityManager } from '@mikro-orm/postgresql';

const em = orm.em as EntityManager;

const qb = em.createQueryBuilder(...);

>

  1. ```typescript
  2. import type { PostgreSqlDriver } from '@mikro-orm/postgresql'; // or any other SQL driver package

  3. const orm = await MikroORM.init<PostgreSqlDriver>({
  4.   entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir`
  5.   dbName: 'my-db-name',
  6.   type: 'postgresql',
  7. });
  8. console.log(orm.em); // access EntityManager via `em` property
  9. ```

There are more ways to configure your entities, take a look at

Read more about all the possible configuration options in Advanced Configuration section.


Then you will need to fork entity manager for each request so their
identity maps will not collide.
To do so, use the RequestContext helper:

  1. ```typescript
  2. const app = express();

  3. app.use((req, res, next) => {
  4.   RequestContext.create(orm.em, next);
  5. });
  6. ```

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.


More info about RequestContext is described here.

Now you can start defining your entities (in one of the entities folders). This is how
simple entity can look like in mongo driver:

./entities/MongoBook.ts

  1. ```typescript
  2. @Entity()
  3. export class MongoBook {

  4.   @PrimaryKey()
  5.   _id: ObjectID;

  6.   @SerializedPrimaryKey()
  7.   id: string;

  8.   @Property()
  9.   title: string;

  10.   @ManyToOne()
  11.   author: Author;

  12.   @ManyToMany()
  13.   tags = new Collection<BookTag>(this);

  14.   constructor(title: string, author: Author) {
  15.     this.title = title;
  16.     this.author = author;
  17.   }

  18. }
  19. ```

For SQL drivers, you can use id: number PK:

./entities/SqlBook.ts

  1. ```typescript
  2. @Entity()
  3. export class SqlBook {

  4.   @PrimaryKey()
  5.   id: number;

  6. }
  7. ```

Or if you want to use UUID primary keys:

./entities/UuidBook.ts

  1. ```typescript
  2. import { v4 } from 'uuid';

  3. @Entity()
  4. export class UuidBook {

  5.   @PrimaryKey()
  6.   uuid = v4();

  7. }
  8. ```

More information can be found in

When you have your entities defined, you can start using ORM either via EntityManager
or via EntityRepositorys.

To 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.

  1. ```typescript
  2. // use constructors in your entities for required parameters
  3. const author = new Author('Jon Snow', 'snow@wall.st');
  4. author.born = new Date();

  5. const publisher = new Publisher('7K publisher');

  6. const book1 = new Book('My Life on The Wall, part 1', author);
  7. book1.publisher = publisher;
  8. const book2 = new Book('My Life on The Wall, part 2', author);
  9. book2.publisher = publisher;
  10. const book3 = new Book('My Life on The Wall, part 3', author);
  11. book3.publisher = publisher;

  12. // just persist books, author and publisher will be automatically cascade persisted
  13. await orm.em.persistAndFlush([book1, book2, book3]);
  14. ```

To fetch entities from database you can use find() and findOne() of EntityManager:

  1. ```typescript
  2. const authors = orm.em.find(Author, {});

  3. for (const author of authors) {
  4.   console.log(author); // instance of Author entity
  5.   console.log(author.name); // Jon Snow

  6.   for (const book of author.books) { // iterating books collection
  7.     console.log(book); // instance of Book entity
  8.     console.log(book.title); // My Life on The Wall, part 1/2/3
  9.   }
  10. }
  11. ```

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

  1. ```typescript
  2. const booksRepository = orm.em.getRepository(Book);

  3. // with sorting, limit and offset parameters, populating author references
  4. const books = await booksRepository.find({ author: '...' }, ['author'], { title: QueryOrder.DESC }, 2, 1);

  5. // or with options object
  6. const books = await booksRepository.find({ author: '...' }, {
  7.   populate: ['author'],
  8.   limit: 1,
  9.   offset: 2,
  10.   orderBy: { title: QueryOrder.DESC },
  11. });

  12. console.log(books); // Book[]
  13. ```

Take 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/).

🤝 Contributing


Contributions, issues and feature requests are welcome. Please read
for details on the process for submitting pull requests to us.

Authors


👤 Martin Adámek

- Twitter: @B4nan
- Github: @b4nan

See also the list of contributors who participated in this project.

Show Your Support


Please ⭐️ this repository if this project helped you!

📝 License


Copyright © 2018 Martin Adámek.

This project is licensed under the MIT License - see the LICENSE file for details.