Gathering detailed insights and metrics for mikro-orm
Gathering detailed insights and metrics for mikro-orm
Gathering detailed insights and metrics for mikro-orm
Gathering detailed insights and metrics for mikro-orm
@mikro-orm/mongodb
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.
@mikro-orm/knex
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.
@mikro-orm/core
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.
@mikro-orm/migrations
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.
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.
npm install mikro-orm
Typescript
Module System
Min. Node Version
Node Version
NPM Version
100
Supply Chain
96.5
Quality
95.4
Maintenance
100
Vulnerability
100
License
TypeScript (99.13%)
JavaScript (0.87%)
Total Downloads
18,130,286
Last Day
27,713
Last Week
175,309
Last Month
857,315
Last Year
8,933,031
7,887 Stars
5,593 Commits
550 Forks
48 Watching
14 Branches
263 Contributors
Minified
Minified + Gzipped
Latest Version
6.4.1
Package Id
mikro-orm@6.4.1
Unpacked Size
18.53 kB
Size
7.22 kB
File Count
6
NPM Version
lerna/8.1.9/node@v22.12.0+arm64 (darwin)
Node Version
22.12.0
Publised On
08 Dec 2024
Cumulative downloads
Total Downloads
Last day
-6%
27,713
Compared to previous day
Last week
-15.1%
175,309
Compared to previous week
Last month
3.9%
857,315
Compared to previous month
Last year
45.5%
8,933,031
Compared to previous year
No dependencies detected.
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity 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 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. (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 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)
.
1const user = await em.findOneOrFail(User, 1); 2user.email = 'foo@bar.com'; 3const car = new Car(); 4user.cars.add(car); 5 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 9await em.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 the User
entity used in previous example:
1@Entity() 2export class User { 3 4 @PrimaryKey() 5 id!: number; 6 7 @Property() 8 name!: string; 9 10 @OneToOne(() => Address) 11 address?: Address; 12 13 @ManyToMany(() => Car) 14 cars = new Collection<Car>(this); 15 16 constructor(name: string) { 17 this.name = name; 18 } 19 20}
Now to create new instance of the User
entity, we are forced to provide the name
:
1const user = new User('John Doe'); // name is required to create new user instance 2user.address = new Address('10 Downing Street'); // address is optional
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.
1const user = await em.findOneOrFail(User, 1, { 2 populate: ['cars', 'address.city'], 3}); 4user.title = 'Mr.'; 5user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity 6user.cars.getItems().forEach(car => car.forSale = true); // cars is 1:m collection of Car entities 7const car = new Car('VW'); 8user.cars.add(car); 9 10// now we can flush all changes done to managed entities 11await em.flush();
em.flush()
will then execute these queries from the example above:
1begin;
2update "user" set "title" = 'Mr.' where "id" = 1;
3update "user_address" set "street" = '10 Downing Street' where "id" = 123;
4update "car"
5 set "for_sale" = case
6 when ("id" = 1) then true
7 when ("id" = 2) then true
8 when ("id" = 3) then true
9 else "for_sale" end
10 where "id" in (1, 2, 3)
11insert into "car" ("brand", "owner") values ('VW', 1);
12commit;
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 with Docusaurus 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
).
QueryBuilder
You can find example integrations for some popular frameworks in the mikro-orm-examples
repository:
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 notsqlite3
as that is already included in the driver package.
1yarn add @mikro-orm/core @mikro-orm/mongodb # for mongo 2yarn add @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb 3yarn add @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb 4yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql 5yarn add @mikro-orm/core @mikro-orm/mssql # for mssql 6yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite 7yarn add @mikro-orm/core @mikro-orm/better-sqlite # for better-sqlite 8yarn add @mikro-orm/core @mikro-orm/libsql # for libsql
or
1npm i -s @mikro-orm/core @mikro-orm/mongodb # for mongo 2npm i -s @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb 3npm i -s @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb 4npm i -s @mikro-orm/core @mikro-orm/postgresql # for postgresql 5npm i -s @mikro-orm/core @mikro-orm/mssql # for mssql 6npm i -s @mikro-orm/core @mikro-orm/sqlite # for sqlite 7npm i -s @mikro-orm/core @mikro-orm/better-sqlite # for better-sqlite 8npm 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 for decorators as well as esModuleInterop
in tsconfig.json
via:
1"experimentalDecorators": true, 2"emitDecoratorMetadata": true, 3"esModuleInterop": true,
Alternatively, you can use EntitySchema
.
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 callingMikroORM.init()
. Alternatively we can cast theorm.em
toEntityManager
exported from the driver package:1import { EntityManager } from '@mikro-orm/postgresql'; 2const em = orm.em as EntityManager; 3const qb = em.createQueryBuilder(...);
1import type { PostgreSqlDriver } from '@mikro-orm/postgresql'; // or any other SQL driver package 2 3const 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}); 8console.log(orm.em); // access EntityManager via `em` property
There are more ways to configure your entities, take a look at installation page.
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:
1const app = express(); 2 3app.use((req, res, next) => { 4 RequestContext.create(orm.em, next); 5});
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 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@Entity() 2export class MongoBook { 3 4 @PrimaryKey() 5 _id: ObjectID; 6 7 @SerializedPrimaryKey() 8 id: string; 9 10 @Property() 11 title: string; 12 13 @ManyToOne(() => Author) 14 author: Author; 15 16 @ManyToMany(() => BookTag) 17 tags = new Collection<BookTag>(this); 18 19 constructor(title: string, author: Author) { 20 this.title = title; 21 this.author = author; 22 } 23 24}
For SQL drivers, you can use id: number
PK:
./entities/SqlBook.ts
1@Entity() 2export class SqlBook { 3 4 @PrimaryKey() 5 id: number; 6 7}
Or if you want to use UUID primary keys:
./entities/UuidBook.ts
1import { v4 } from 'uuid'; 2 3@Entity() 4export class UuidBook { 5 6 @PrimaryKey() 7 uuid = v4(); 8 9}
More information can be found in defining entities section in docs.
When you have your entities defined, you can start using ORM either via EntityManager
or via EntityRepository
s.
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// use constructors in your entities for required parameters 2const author = new Author('Jon Snow', 'snow@wall.st'); 3author.born = new Date(); 4 5const publisher = new Publisher('7K publisher'); 6 7const book1 = new Book('My Life on The Wall, part 1', author); 8book1.publisher = publisher; 9const book2 = new Book('My Life on The Wall, part 2', author); 10book2.publisher = publisher; 11const book3 = new Book('My Life on The Wall, part 3', author); 12book3.publisher = publisher; 13 14// just persist books, author and publisher will be automatically cascade persisted 15await em.persistAndFlush([book1, book2, book3]);
To fetch entities from database you can use find()
and findOne()
of EntityManager
:
1const authors = em.find(Author, {}, { populate: ['books'] }); 2 3for (const author of authors) { 4 console.log(author); // instance of Author entity 5 console.log(author.name); // Jon Snow 6 7 for (const book of author.books) { // iterating books collection 8 console.log(book); // instance of Book entity 9 console.log(book.title); // My Life on The Wall, part 1/2/3 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:
1const booksRepository = em.getRepository(Book); 2 3const books = await booksRepository.find({ author: '...' }, { 4 populate: ['author'], 5 limit: 1, 6 offset: 2, 7 orderBy: { title: QueryOrder.DESC }, 8}); 9 10console.log(books); // Loaded<Book, 'author'>[]
Take a look at docs about working with EntityManager
or using EntityRepository
instead.
Contributions, issues and feature requests are welcome. Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.
👤 Martin Adámek
See also the list of contributors who participated in this project.
Please ⭐️ this repository if this project helped you!
Copyright © 2018 Martin Adámek.
This project is licensed under the MIT License - see the LICENSE file for details.
No vulnerabilities found.
Reason
30 commit(s) and 16 issue activity found in the last 90 days -- score normalized to 10
Reason
license file detected
Details
Reason
no dangerous workflow patterns detected
Reason
security policy file detected
Details
Reason
SAST tool is run on all commits
Details
Reason
no binaries found in the repo
Reason
1 existing vulnerabilities detected
Details
Reason
Found 1/25 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
project is not fuzzed
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Score
Last Scanned on 2024-12-02
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More