Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
mikro-orm
Advanced tools
Simple typescript ORM for node.js based on data-mapper, unit-of-work and identity-map patterns. Supports MongoDB, MySQL and SQLite databases.
Mikro-ORM is a TypeScript ORM for Node.js based on Data Mapper, Unit of Work, and Identity Map patterns. It supports multiple databases including MongoDB, MySQL, PostgreSQL, SQLite, and MariaDB. It provides a powerful and flexible way to interact with your database using TypeScript and JavaScript.
Entity Definition
Defines an entity with properties that map to database columns. The `@Entity` decorator marks the class as a database entity, while `@PrimaryKey` and `@Property` decorators define the primary key and other properties respectively.
```typescript
import { Entity, PrimaryKey, Property } from 'mikro-orm';
@Entity()
class User {
@PrimaryKey()
id!: number;
@Property()
name!: string;
@Property()
email!: string;
}
```
CRUD Operations
Demonstrates basic Create, Read, Update, and Delete (CRUD) operations. The `persistAndFlush` method saves a new entity to the database, and the `find` method retrieves entities from the database.
```typescript
const user = new User();
user.name = 'John Doe';
user.email = 'john.doe@example.com';
await orm.em.persistAndFlush(user);
const users = await orm.em.find(User, {});
console.log(users);
```
Query Builder
Shows how to use the query builder to construct and execute complex queries. The `createQueryBuilder` method creates a new query builder instance, and the `select` and `where` methods build the query.
```typescript
const qb = orm.em.createQueryBuilder(User);
const users = await qb.select('*').where({ name: 'John Doe' }).execute();
console.log(users);
```
Transactions
Illustrates how to perform operations within a transaction. The `transactional` method ensures that all operations within the callback are executed within a single transaction.
```typescript
await orm.em.transactional(async em => {
const user = new User();
user.name = 'Jane Doe';
user.email = 'jane.doe@example.com';
await em.persistAndFlush(user);
});
```
TypeORM is another TypeScript ORM for Node.js that supports Active Record and Data Mapper patterns. It is highly popular and supports multiple databases. Compared to Mikro-ORM, TypeORM has a larger community and more extensive documentation, but Mikro-ORM offers a more modern and flexible API.
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It is known for its simplicity and ease of use. While Sequelize is more mature and has a larger user base, Mikro-ORM provides better TypeScript support and more advanced features like Unit of Work and Identity Map patterns.
Objection.js is an SQL-friendly ORM for Node.js, built on top of the SQL query builder Knex.js. It aims to stay as close to the SQL syntax as possible while providing a powerful and flexible API. Compared to Mikro-ORM, Objection.js offers more control over raw SQL queries but lacks some of the higher-level abstractions and features provided by Mikro-ORM.
Simple typescript ORM for node.js based on data-mapper, unit-of-work and identity-map patterns. Supports MongoDB, MySQL and SQLite databases.
Heavily inspired by Doctrine and Nextras Orm.
MikroORM's documentation, included in this repo in the root directory, is built with Jekyll and publicly hosted on GitHub Pages at https://b4nan.github.io/mikro-orm/.
Fist install the module via yarn
or npm
and do not forget to install the database driver as well:
$ yarn add mikro-orm mongodb # for mongo
$ yarn add mikro-orm mysql2 # for mysql
$ yarn add mikro-orm sqlite # for sqlite
or
$ npm i -s mikro-orm mongodb # for mongo
$ npm i -s mikro-orm mysql2 # for mysql
$ npm i -s mikro-orm sqlite # for sqlite
Then call MikroORM.init
as part of bootstrapping your app:
const orm = await MikroORM.init({
entitiesDirs: ['entities'], // relative to `baseDir`
dbName: 'my-db-name',
clientUrl: '...', // defaults to 'mongodb://localhost:27017' for mongodb driver
});
console.log(orm.em); // access EntityManager via `em` property
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:
const app = express();
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
More info about RequestContext
is described here.
Now you can start defining your entities (in one of the entitiesDirs
folders):
./entities/book.ts
@Entity()
export class Book {
@PrimaryKey()
_id: ObjectID;
@Property()
title: string;
@ManyToOne()
author: Author;
@ManyToMany({ entity: () => BookTag.name, inversedBy: 'books' })
tags = new Collection<BookTag>(this);
constructor(title: string, author: Author) {
this.title = title;
this.author = author;
}
}
export interface Book extends IEntity { }
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.
// use constructors in your entities for required parameters
const author = new Author('Jon Snow', 'snow@wall.st');
author.born = new Date();
const publisher = new Publisher('7K publisher');
const book1 = new Book('My Life on The Wall, part 1', author);
book1.publisher = publisher;
const book2 = new Book('My Life on The Wall, part 2', author);
book2.publisher = publisher;
const book3 = new Book('My Life on The Wall, part 3', author);
book3.publisher = publisher;
// just persist books, author and publisher will be automatically cascade persisted
await orm.em.persist([book1, book2, book3]);
To fetch entities from database you can use find()
and findOne()
of EntityManager
:
const authors = orm.em.find(Author.name, {});
for (const author of authors) {
console.log(author); // instance of Author entity
console.log(author.name); // Jon Snow
for (const book of author.books) { // iterating books collection
console.log(book); // instance of Book entity
console.log(book.title); // My Life on The Wall, part 1/2/3
}
}
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:
const booksRepository = orm.em.getRepository<Book>(Book.name);
const books = await booksRepository.find({ author: '...' }, ['author'], { title: -1 });
console.log(books); // Book[]
Take a look at docs about working with EntityManager
or using EntityRepository
instead.
FAQs
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.
The npm package mikro-orm receives a total of 173,180 weekly downloads. As such, mikro-orm popularity was classified as popular.
We found that mikro-orm demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.