Article From:


nestIt is a node.js framework compatible with typescript and JavaScript. In this paper, we use some basic modules of nest to build a simple web CURD application. TypeORM is a relatively mature object relational mapping device.It’s written by typescript. The introduction of nest and typeORM can view official documents.

Project construction

Using CLI to build project:

 npm i -g @nestjs/cli
 nest new nest-app

This creates a nest-app project. After creation, the following core files are included in the SRC folder:

├── app.controller.ts
├── app.module.ts
└── main.ts

main.tsAsk the project startup file, default listening port 3000, root module app.module.ts, routing instance app.controller.ts.

Now execute the following command to run the project:

npm run start

After startup, enter localhost:3000 in the browser, you can see Hello world.


Install typeorm:

npm install --save @nestjs/typeorm typeorm mysql

typeormSupport for multiple databases. This project uses mysql.

Create the entity employee and company, the file directory:

├── employee.entity.ts
├── company.entity.ts
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, JoinTable } from 'typeorm';
import { Company } from './company.entity'
export class Employee {
    id: number

    name: string

    age: number

    address: string

    @ManyToOne(type => Company, company => company.employees, { cascade: true })
    company: Company


import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import { Employee } from './employee.entity'
export class Company {
    id: number

    name: string

    @OneToMany(type => Employee, employee =>
    employees: Employee[]

In typeorm, the object mapping relationship is specified by the decorator. The main use of this project entity is the use of the basic functions such as self growth key, data column, and one to many relationships. The relationship must be clear when defining the relationship between entity objects, and this example uses cascade.For cascading delete cascaded save operations. Note: cascading deletions and cascading guarantees will only take effect when save () is applied, but not at insert ().

Create a employee module

├── employee.controller.ts
├── employee.module.ts
└── employee.service.ts


import { Injectable } from '@nestjs/common';
import { Employee } from '../entities/employee.entity'
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Company } from '../entities/company.entity'

export class EmployeeService {

    private readonly employeeRepository: Repository<Employee>) { }
    root(): string {
        return 'Hello World!';
    async create(): Promise<string> {
        let employee = new Employee();
        let company = new Company(); = 'asc'; = 'novak';
        employee.age = 20;
        employee.address = 'shanghai'; = company;

            .then(res => {
                return 'create employee ...done'
            .catch(err => {
                return err

    async findOne(name: string): Promise<Employee> {
        return await this.employeeRepository.findOne({ name: name });
import { Get, Controller,Param } from ‘@nestjs/common’;
import { EmployeeService } from ‘./employee.service’;
import { Employee } from ‘entities/employee.entity’;


export class EmployeeController {
constructor(private readonly employeeService: EmployeeService) {}


return this.employeeService.root();


async findOne(@Param() params):Promise<Employee>{
return this.employeeService.findOne(;


async create():Promise<string>{
return this.employeeService.create();


import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { EmployeeController } from './employee.controller'
import { EmployeeService } from './employee.service'
import { Employee } from '../entities/employee.entity'

    imports: [TypeOrmModule.forFeature([Employee])],
    providers: [EmployeeService],
    controllers: [EmployeeController]
export class EmployeeModule {
In employee.module.ts, TypeOrmModule.forFeature () is used to dynamically acquire module objects. The basic routing configuration is used in employee.controller.ts.

Module injection, database connection information configuration

Inject the employee module in the root directory:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import {EmployeeModule} from './employee/employee.module'

  imports: [
  controllers: [AppController],
  providers: [AppService],
export class AppModule { }

As you can see, using typeormmodule.forRoot () in imports for dynamic return to typeormmodule, typeormmodule connects databases with a variety of ways to use configuration files or in forThe options parameter information is introduced into Root (). This example uses a configuration file to add ormconfig.json files in the SRC directory.

    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "root",
    "password": "root",
    "database": "nest-app",
    "entities": ["src/**/**.entity{.ts,.js}"],
    "synchronize": true

At this point, a basic service program with the creation and query capabilities of employee has been built, and the browser is entered: localhost:3000/employee/create to see the effect.

Source code GitHub

Welcome small partners to exchange! Square

Similar Posts:

Link of this Article: Basic use of nest.js + typeORM:

One Reply to “Basic use of nest.js + typeORM:”

Leave a Reply

Your email address will not be published. Required fields are marked *