Migration from Sequelize to TypeORM

Setting up a connection

In sequelize you create a connection this way:

  1. const sequelize = new Sequelize("database", "username", "password", {
  2. host: "localhost",
  3. dialect: "mysql"
  4. });
  5. sequelize
  6. .authenticate()
  7. .then(() => {
  8. console.log("Connection has been established successfully.");
  9. })
  10. .catch(err => {
  11. console.error("Unable to connect to the database:", err);
  12. });

In TypeORM you create a connection like this:

  1. import {createConnection} from "typeorm";
  2. createConnection({
  3. type: "mysql",
  4. host: "localhost",
  5. username: "username",
  6. password: "password"
  7. }).then(connection => {
  8. console.log("Connection has been established successfully.");
  9. })
  10. .catch(err => {
  11. console.error("Unable to connect to the database:", err);
  12. });

Then you can get your connection instance from anywhere in your app using getConnection.

Learn more about Connections

Schema synchronization

In sequelize you do schema synchronization this way:

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

In TypeORM you just add synchronize: true in the connection options:

  1. createConnection({
  2. type: "mysql",
  3. host: "localhost",
  4. username: "username",
  5. password: "password",
  6. synchronize: true
  7. });

Creating a models

This is how models are defined in sequelize:

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

In TypeORM these models are called entities and you can define them like this:

  1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
  2. @Entity()
  3. export class Project {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. title: string;
  8. @Column()
  9. description: string;
  10. }
  1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
  2. @Entity()
  3. export class Task {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. title: string;
  8. @Column("text")
  9. description: string;
  10. @Column()
  11. deadline: Date;
  12. }

It’s highly recommended to define one entity class per file.TypeORM allows you to use your classes as database modelsand provides a declarative way to define what part of your modelwill 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:

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

Can be achieved in TypeORM like this:

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

Following in sequelize:

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

Is written like this in TypeORM:

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

Following in sequelize:

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

Can be achieved this way in TypeORM:

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

Following in sequelize:

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

Translates to this in TypeORM:

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

Following in sequelize:

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

Can be achieved this way in TypeORM:

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

Following in sequelize:

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

Can be achieved this way in TypeORM:

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

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

  1. @CreateDateColumn();
  2. createDate: Date;
  3. @UpdateDateColumn();
  4. updateDate: Date;

Working with models

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

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

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

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

or active record pattern

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

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

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

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

To access properties in sequelize you do the following:

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

In TypeORM you simply do:

  1. console.log(employee.name);

To create an index in sequelize you do:

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

In TypeORM you do:

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

Learn more about Indices