So far, in this series, we’ve used a few different solutions for managing databases. To work with MongoDB, we’ve used Mongoose. To manage a PostgreSQL database, we’ve utilized TypeORM and Prisma. This article looks into another Object-relational mapping (ORM) library called MikroORM. By having a broad perspective on what’s available, we can choose the library that fits our needs the most.
You can find all of the code from this article in this repository.
Setting up MikroORM and PostgreSQL
The most straightforward way to use PostgreSQL in our project is to use Docker. In the second part of this series, we set up PostgreSQL and TypeORM. Therefore, we can use the same docker-compose.yml file we created back then.
1version: "3"
2services:
3 postgres:
4 container_name: nestjs-postgres
5 image: postgres:latest
6 ports:
7 - "5432:5432"
8 volumes:
9 - /data/postgres:/data/postgres
10 env_file:
11 - docker.env
12 networks:
13 - postgres
14
15 pgadmin:
16 links:
17 - postgres:postgres
18 container_name: nestjs-pgadmin
19 image: dpage/pgadmin4
20 ports:
21 - "8080:80"
22 volumes:
23 - /data/pgadmin:/root/.pgadmin
24 env_file:
25 - docker.env
26 networks:
27 - postgres
28
29networks:
30 postgres:
31 driver: bridgeAlso, we need to create a file that contains the variables our docker container needs.
1POSTGRES_USER=admin
2POSTGRES_PASSWORD=admin
3POSTGRES_DB=nestjs
4PGADMIN_DEFAULT_EMAIL=admin@admin.com
5PGADMIN_DEFAULT_PASSWORD=adminConnecting to the database
To be able to connect to the database, we need to establish a set of environment variables our NestJS application will use.
1import { Module } from '@nestjs/common';
2import { ConfigModule } from '@nestjs/config';
3import * as Joi from 'joi';
4
5@Module({
6 imports: [
7 ConfigModule.forRoot({
8 validationSchema: Joi.object({
9 POSTGRES_HOST: Joi.string().required(),
10 POSTGRES_PORT: Joi.number().required(),
11 POSTGRES_USER: Joi.string().required(),
12 POSTGRES_PASSWORD: Joi.string().required(),
13 POSTGRES_DB: Joi.string().required(),
14 }),
15 }),
16 ],
17 controllers: [],
18 providers: [],
19})
20export class AppModule {}We also need to create a file that contains the values for the variables we’ve defined above.
1POSTGRES_HOST=localhost
2POSTGRES_PORT=5432
3POSTGRES_USER=admin
4POSTGRES_PASSWORD=admin
5POSTGRES_DB=nestjsIn this series, we use PostgreSQL. Because of that, we need the @mikroorm/postgresql package, among others.
1npm install @mikro-orm/core @mikro-orm/nestjs @mikro-orm/postgresqlWith all of the above, we can create our DatabaseModule that establishes a connection to the database.
1import { Module } from '@nestjs/common';
2import { ConfigModule, ConfigService } from '@nestjs/config';
3import { MikroOrmModule } from '@mikro-orm/nestjs';
4
5@Module({
6 imports: [
7 MikroOrmModule.forRootAsync({
8 imports: [ConfigModule],
9 inject: [ConfigService],
10 useFactory: (configService: ConfigService) => ({
11 dbName: configService.get('POSTGRES_DB'),
12 user: configService.get('POSTGRES_USER'),
13 password: configService.get('POSTGRES_PASSWORD'),
14 host: configService.get('POSTGRES_HOST'),
15 port: configService.get('POSTGRES_PORT'),
16 type: 'postgresql',
17 autoLoadEntities: true,
18 }),
19 }),
20 ],
21})
22export class DatabaseModule {}Don’t forget to import the DatabaseModule in the AppModule.
Defining a basic entity
Thanks to using the autoLoadEntities property, MikroORM loads the entities we define. First, let’s create an elementary entity for a post. To do that, we can use a set of decorators provided by the @mikro-orm/core package.
1import { Entity, Property, PrimaryKey } from '@mikro-orm/core';
2
3@Entity()
4class PostEntity {
5 @PrimaryKey()
6 id: number;
7
8 @Property()
9 title: string;
10
11 @Property()
12 content: string;
13}
14
15export default PostEntity;For MikroORM to detect the above entity, we need to register it in the module.
1import { Module } from '@nestjs/common';
2import { PostsService } from './posts.service';
3import PostsController from './posts.controller';
4import { MikroOrmModule } from '@mikro-orm/nestjs';
5import PostEntity from './post.entity';
6
7@Module({
8 imports: [MikroOrmModule.forFeature([PostEntity])],
9 controllers: [PostsController],
10 providers: [PostsService],
11})
12export class PostsModule {}Interacting with the entities
The above file mentions the PostsController and PostsService. Let’s start by creating the latter.
1import { Injectable } from '@nestjs/common';
2import { InjectRepository } from '@mikro-orm/nestjs';
3import { EntityRepository } from '@mikro-orm/core';
4import PostEntity from './post.entity';
5
6@Injectable()
7export class PostsService {
8 constructor(
9 @InjectRepository(PostEntity)
10 private readonly postRepository: EntityRepository<PostEntity>,
11 ) {}
12}MikroORM uses a widespread repository pattern. We can easily create, modify, fetch, and delete entities with it.
Getting all entities
To get a whole list of entities from our database, we can use the findAll method.
1getPosts() {
2 return this.postRepository.findAll();
3}Getting an entity with a given id
Besides the above, we also have the findOne method. If we provide it with the correct argument, we can fetch a post with a given id.
1async getPostById(id: number) {
2 const post = await this.postRepository.findOne({
3 id,
4 });
5 if (!post) {
6 throw new PostNotFoundException(id);
7 }
8 return post;
9}We could also use the above method to find a post with a particular title, for example.
We use the PostNotFoundException, which is a custom exception.
1import { NotFoundException } from '@nestjs/common';
2
3class PostNotFoundException extends NotFoundException {
4 constructor(postId: number) {
5 super(`Post with id ${postId} not found`);
6 }
7}
8
9export default PostNotFoundException;MikroORM uses the Identity Map pattern to track the data. Whenever we fetch an entity from the database, MikroORM keeps its reference. This allows for a bunch of optimizations. For example, fetching a post with the same id twice returns the same instance and runs only one SELECT query.
1const firstPost = await this.postRepository.findOne({ id: 1 });
2const secondPost = await this.postRepository.findOne({ id: 1 });
3
4console.log(firstPost === secondPost); // trueCreating an entity
MikroORM handles transactions automatically and aims to batch as many of our queries as possible. Because of that, we need to tell MikroORM to persist changes to the database explicitly.
If you want to know more about transactions, check out API with NestJS #15. Defining transactions with PostgreSQL and TypeORM
1const newPost = await this.postRepository.create(post);
2newPost.persist();We call the persist method to mark the entity as something we want to synchronize with the database.
When we later call the flush() method, MikroORM stores all of the changes we’ve marked with the persist method to the database.
1await this.postRepository.flush();We can combine both of the above actions by using the persistAndFlush method.
1async createPost(post: CreatePostDto) {
2 const newPost = await this.postRepository.create(post);
3 await this.postRepository.persistAndFlush(newPost);
4 return newPost;
5}Editing an entity
To modify an entity, we can get it from the database and modify it. Then, when we flush all of the changes, MikroORM persists them in the database.
1async updatePost(id: number, post: UpdatePostDto) {
2 const existingPost = await this.getPostById(id);
3
4 existingPost.content = post.content;
5 existingPost.title = post.title;
6
7 await this.postRepository.persistAndFlush(existingPost);
8 return existingPost;
9}We can simplify the above code by using the wrap function provided by MikroORM. It allows us to use various helpers, such as assign.
1async updatePost(id: number, post: UpdatePostDto) {
2 const existingPost = await this.getPostById(id);
3 wrap(existingPost).assign(post);
4 await this.postRepository.persistAndFlush(existingPost);
5 return existingPost;
6}By default, assign does not merge objects recursively. To achieve that, we would need to use wrap(existingPost).assign(post, { mergeObjects: true }) instead.
Please notice that using assign allows us to implement the PATCH method, not PUT. The above is because it won’t remove properties if we don’t explicitly set them as null.
Removing an entity
We need to mark the entity for removal and flush the changes to remove an entity.
1async deletePost(id: number) {
2 const post = await this.getPostById(id);
3 this.postRepository.remove(post);
4 return this.postRepository.flush();
5}We can simplify the above function by using the removeAndFlush method.
1async deletePost(id: number) {
2 const post = await this.getPostById(id);
3 return this.postRepository.removeAndFlush(post);
4}Putting all of the features together
When we incorporate all of the above features into our service, it looks like that:
1import { Injectable } from '@nestjs/common';
2import { InjectRepository } from '@mikro-orm/nestjs';
3import { EntityRepository, wrap } from '@mikro-orm/core';
4import PostEntity from './post.entity';
5import PostNotFoundException from './exceptions/postNotFound.exception';
6import CreatePostDto from './dto/createPost.dto';
7import UpdatePostDto from './dto/updatePost.dto';
8
9@Injectable()
10export class PostsService {
11 constructor(
12 @InjectRepository(PostEntity)
13 private readonly postRepository: EntityRepository<PostEntity>,
14 ) {}
15
16 getPosts() {
17 return this.postRepository.findAll();
18 }
19
20 async getPostById(id: number) {
21 const post = await this.postRepository.findOne({
22 id,
23 });
24 if (!post) {
25 throw new PostNotFoundException(id);
26 }
27 return post;
28 }
29
30 async createPost(post: CreatePostDto) {
31 const newPost = await this.postRepository.create(post);
32 await this.postRepository.persistAndFlush(newPost);
33 return newPost;
34 }
35
36 async updatePost(id: number, post: UpdatePostDto) {
37 const existingPost = await this.getPostById(id);
38 wrap(existingPost).assign(post);
39 await this.postRepository.persistAndFlush(existingPost);
40 return existingPost;
41 }
42
43 async deletePost(id: number) {
44 const post = await this.getPostById(id);
45 return this.postRepository.removeAndFlush(post);
46 }
47}We also need a controller that uses our service.
1import {
2 Body,
3 Controller,
4 Delete,
5 Get,
6 Param,
7 Post,
8 Put,
9} from '@nestjs/common';
10import { PostsService } from './posts.service';
11import FindOneParams from '../utils/findOneParams';
12import CreatePostDto from './dto/createPost.dto';
13import UpdatePostDto from './dto/updatePost.dto';
14
15@Controller('posts')
16export default class PostsController {
17 constructor(private readonly postsService: PostsService) {}
18
19 @Get()
20 async getPosts() {
21 return this.postsService.getPosts();
22 }
23
24 @Get(':id')
25 getPostById(@Param() { id }: FindOneParams) {
26 return this.postsService.getPostById(id);
27 }
28
29 @Post()
30 async createPost(@Body() post: CreatePostDto) {
31 return this.postsService.createPost(post);
32 }
33
34 @Put(':id')
35 async updatePost(
36 @Param() { id }: FindOneParams,
37 @Body() post: UpdatePostDto,
38 ) {
39 return this.postsService.updatePost(id, post);
40 }
41
42 @Delete(':id')
43 async deletePost(@Param() { id }: FindOneParams) {
44 return this.postsService.deletePost(Number(id));
45 }
46}Synchronizing our entities schema with the database
Doing all of the above does not create a posts table in our database. To achieve that, we need to create a migration. We will need the MikroORM CLI and a dedicated @mikro-orm/cli package.
1npm install @mikro-orm/cli @mikro-orm/migrationsThe CLI needs a separate configuration. To provide it, let’s add the following to the package.json first:
1"mikro-orm": {
2 "useTsNode": true,
3 "configPaths": [
4 "./src/mikro-orm.config.ts"
5 ]
6}We also need to create the mikro-orm.config.ts file in the src directory.
1import PostEntity from './posts/post.entity';
2import { Options } from '@mikro-orm/core';
3import { ConfigService } from '@nestjs/config';
4
5const configService = new ConfigService();
6
7const MikroOrmConfig: Options = {
8 entities: [PostEntity],
9 type: 'postgresql',
10 dbName: configService.get('POSTGRES_DB'),
11 user: configService.get('POSTGRES_USER'),
12 password: configService.get('POSTGRES_PASSWORD'),
13 host: configService.get('POSTGRES_HOST'),
14 port: configService.get('POSTGRES_PORT'),
15};
16
17export default MikroOrmConfig;Because the mikro-orm.config.ts is not a part of a NestJS application, we initialize the ConfigService manually.
When we run npx mikro-orm migration:create, MikroORM checks the difference between our entity schema definitions and the state of the database. If there is a difference, it generates migration files.
1import { Migration } from '@mikro-orm/migrations';
2
3export class Migration20220522201347 extends Migration {
4
5 async up(): Promise<void> {
6 this.addSql('create table "post_entity" ("id" serial primary key, "title" varchar(255) not null, "content" varchar(255) not null);');
7 }
8
9 async down(): Promise<void> {
10 this.addSql('drop table if exists "post_entity" cascade;');
11 }
12
13}When we run npx mikro-orm migration:up, MikroORM performs the above migrations to bring our database to the latest state.
MikroORM keeps track of all of the migrations in the mikro_orm_migrations table.
Summary
In this article, we’ve gone through using MikroORM with PostgreSQL and NestJS. It included learning how MikroORM works by implementing all of the Create, Read, Update and Delete (CRUD) operations. To do that, we had to understand how MikroORM works under the hood and how to synchronize changes with the database. We also learned the basics of migrations and created them using the MikroORM CLI.