# Migration from Sequelize to TypeORM

# Setting up a data source

In sequelize you create a data source this way:

const sequelize = new Sequelize("database", "username", "password", {
    host: "localhost",
    dialect: "mysql",
})

sequelize
    .authenticate()
    .then(() => {
        console.log("Data Source has been initialized successfully.")
    })
    .catch((err) => {
        console.error("Error during Data Source initialization:", err)
    })
1
2
3
4
5
6
7
8
9
10
11
12
13

In TypeORM you create a data source following way:

import { DataSource } from "typeorm"

const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    username: "username",
    password: "password",
})

dataSource
    .initialize()
    .then(() => {
        console.log("Data Source has been initialized successfully.")
    })
    .catch((err) => {
        console.error("Error during Data Source initialization:", err)
    })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Then you can use dataSource instance from anywhere in your app.

Learn more about Data Source

# Schema synchronization

In sequelize you do schema synchronization this way:

Project.sync({ force: true })
Task.sync({ force: true })
1
2

In TypeORM you just add synchronize: true in the data source options:

const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    username: "username",
    password: "password",
    synchronize: true,
})
1
2
3
4
5
6
7

# Creating a models

This is how models are defined in sequelize:

module.exports = function (sequelize, DataTypes) {
    const Project = sequelize.define("project", {
        title: DataTypes.STRING,
        description: DataTypes.TEXT,
    })

    return Project
}
1
2
3
4
5
6
7
8
module.exports = function (sequelize, DataTypes) {
    const Task = sequelize.define("task", {
        title: DataTypes.STRING,
        description: DataTypes.TEXT,
        deadline: DataTypes.DATE,
    })

    return Task
}
1
2
3
4
5
6
7
8
9

In TypeORM these models are called entities and you can define them the following way:

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Project {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    description: string
}
1
2
3
4
5
6
7
8
9
10
11
12
13
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Task {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column("text")
    description: string

    @Column()
    deadline: Date
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

It's highly recommended defining one entity class per file. TypeORM allows you to use your classes as database models and provides a declarative way to define what part of your model will become part of your database table. The power of TypeScript gives you type hinting and other useful features that you can use in classes.

Learn more about Entities and columns

# Other model settings

The following in sequelize:

flag: { type: Sequelize.BOOLEAN, allowNull: true, defaultValue: true },
1

Can be achieved in TypeORM like this:

@Column({ nullable: true, default: true })
flag: boolean;
1
2

Following in sequelize:

flag: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }
1

Is written like this in TypeORM:

@Column({ default: () => "NOW()" })
myDate: Date;
1
2

Following in sequelize:

someUnique: { type: Sequelize.STRING, unique: true },
1

Can be achieved this way in TypeORM:

@Column({ unique: true })
someUnique: string;
1
2

Following in sequelize:

fieldWithUnderscores: { type: Sequelize.STRING, field: "field_with_underscores" },
1

Translates to this in TypeORM:

@Column({ name: "field_with_underscores" })
fieldWithUnderscores: string;
1
2

Following in sequelize:

incrementMe: { type: Sequelize.INTEGER, autoIncrement: true },
1

Can be achieved this way in TypeORM:

@Column()
@Generated()
incrementMe: number;
1
2
3

Following in sequelize:

identifier: { type: Sequelize.STRING, primaryKey: true },
1

Can be achieved this way in TypeORM:

@Column({ primary: true })
identifier: string;
1
2

To create createDate and updateDate-like columns you need to defined two columns (name it what you want) in your entity:

@CreateDateColumn();
createDate: Date;

@UpdateDateColumn();
updateDate: Date;
1
2
3
4
5

# Working with models

To create and save a new model in sequelize you write:

const employee = await Employee.create({
    name: "John Doe",
    title: "senior engineer",
})
1
2
3
4

In TypeORM there are several ways to create and save a new model:

const employee = new Employee() // you can use constructor parameters as well
employee.name = "John Doe"
employee.title = "senior engineer"
await dataSource.getRepository(Employee).save(employee)
1
2
3
4

or active record pattern

const employee = Employee.create({ name: "John Doe", title: "senior engineer" })
await employee.save()
1
2

if you want to load an existing entity from the database and replace some of its properties you can use the following method:

const employee = await Employee.preload({ id: 1, name: "John Doe" })
1

Learn more about Active Record vs Data Mapper and Repository API.

To access properties in sequelize you do the following:

console.log(employee.get("name"))
1

In TypeORM you simply do:

console.log(employee.name)
1

To create an index in sequelize you do:

sequelize.define(
    "user",
    {},
    {
        indexes: [
            {
                unique: true,
                fields: ["firstName", "lastName"],
            },
        ],
    },
)
1
2
3
4
5
6
7
8
9
10
11
12

In TypeORM you do:

@Entity()
@Index(["firstName", "lastName"], { unique: true })
export class User {}
1
2
3

Learn more about Indices