从 Sequelize 迁移到 TypeORM
配置数据源
在 sequelize 中你这样创建数据源:
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)
})在 TypeORM 中你按下面的方式创建数据源:
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)
})之后你就可以在应用的任何地方使用 dataSource 实例了。
进一步了解数据源
结构同步
在 sequelize 中你这样进行结构同步:
Project.sync({ force: true })
Task.sync({ force: true })在 TypeORM 中你只需在数据源选项里加上 synchronize: true:
const dataSource = new DataSource({
type: "mysql",
host: "localhost",
username: "username",
password: "password",
synchronize: true,
})创建模型
这是 sequelize 中定义模型的方式:
module.exports = function (sequelize, DataTypes) {
const Project = sequelize.define("project", {
title: DataTypes.STRING,
description: DataTypes.TEXT,
})
return Project
}module.exports = function (sequelize, DataTypes) {
const Task = sequelize.define("task", {
title: DataTypes.STRING,
description: DataTypes.TEXT,
deadline: DataTypes.DATE,
})
return Task
}在 TypeORM 中这些模型被称为实体,你可以按下面的方式定义它们:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class Project {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
description: string
}import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class Task {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column("text")
description: string
@Column()
deadline: Date
}强烈建议每个文件只定义一个实体类。TypeORM 允许你把自己的类用作数据库模型,并提供了一种声明式方式来定义模型的哪一部分会成为数据库表的一部分。TypeScript 的能力为你提供了类型提示以及其他可在类中使用的实用特性。
进一步了解实体与列
其他模型设置
sequelize 中的下面这段:
flag: { type: Sequelize.BOOLEAN, allowNull: true, defaultValue: true },在 TypeORM 中可以这样实现:
@Column({ nullable: true, default: true })
flag: boolean;sequelize 中的下面这段:
flag: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }在 TypeORM 中这样写:
@Column({ default: () => "NOW()" })
myDate: Date;sequelize 中的下面这段:
someUnique: { type: Sequelize.STRING, unique: true },在 TypeORM 中可以这样实现:
@Column({ unique: true })
someUnique: string;sequelize 中的下面这段:
fieldWithUnderscores: { type: Sequelize.STRING, field: "field_with_underscores" },在 TypeORM 中对应:
@Column({ name: "field_with_underscores" })
fieldWithUnderscores: string;sequelize 中的下面这段:
incrementMe: { type: Sequelize.INTEGER, autoIncrement: true },在 TypeORM 中可以这样实现:
@Column()
@Generated()
incrementMe: number;sequelize 中的下面这段:
identifier: { type: Sequelize.STRING, primaryKey: true },在 TypeORM 中可以这样实现:
@Column({ primary: true })
identifier: string;要创建类似 createDate 和 updateDate 的列,你需要在实体中定义两个列(名字随你取):
@CreateDateColumn();
createDate: Date;
@UpdateDateColumn();
updateDate: Date;操作模型
在 sequelize 中要创建并保存一个新模型,你这样写:
const employee = await Employee.create({
name: "John Doe",
title: "senior engineer",
})在 TypeORM 中有几种方式可以创建并保存新模型:
const employee = new Employee() // 你也可以使用构造函数参数
employee.name = "John Doe"
employee.title = "senior engineer"
await dataSource.getRepository(Employee).save(employee)或者用 active record 模式
const employee = Employee.create({ name: "John Doe", title: "senior engineer" })
await employee.save()如果你想从数据库加载一个已有实体并替换它的某些属性,可以使用以下方法:
const employee = await Employee.preload({ id: 1, name: "John Doe" })进一步了解 Active Record 与 Data Mapper 和 Repository API。
在 sequelize 中要访问属性,你这样做:
console.log(employee.get("name"))在 TypeORM 中你只需:
console.log(employee.name)在 sequelize 中要创建索引,你这样做:
sequelize.define(
"user",
{},
{
indexes: [
{
unique: true,
fields: ["firstName", "lastName"],
},
],
},
)在 TypeORM 中你这样做:
@Entity()
@Index(["firstName", "lastName"], { unique: true })
export class User {}进一步了解索引
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)
})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)
})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 })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,
})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
}module.exports = function (sequelize, DataTypes) {
const Task = sequelize.define("task", {
title: DataTypes.STRING,
description: DataTypes.TEXT,
deadline: DataTypes.DATE,
})
return Task
}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
}import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class Task {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column("text")
description: string
@Column()
deadline: Date
}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 },Can be achieved in TypeORM like this:
@Column({ nullable: true, default: true })
flag: boolean;Following in sequelize:
flag: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }Is written like this in TypeORM:
@Column({ default: () => "NOW()" })
myDate: Date;Following in sequelize:
someUnique: { type: Sequelize.STRING, unique: true },Can be achieved this way in TypeORM:
@Column({ unique: true })
someUnique: string;Following in sequelize:
fieldWithUnderscores: { type: Sequelize.STRING, field: "field_with_underscores" },Translates to this in TypeORM:
@Column({ name: "field_with_underscores" })
fieldWithUnderscores: string;Following in sequelize:
incrementMe: { type: Sequelize.INTEGER, autoIncrement: true },Can be achieved this way in TypeORM:
@Column()
@Generated()
incrementMe: number;Following in sequelize:
identifier: { type: Sequelize.STRING, primaryKey: true },Can be achieved this way in TypeORM:
@Column({ primary: true })
identifier: string;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;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",
})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)or active record pattern
const employee = Employee.create({ name: "John Doe", title: "senior engineer" })
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:
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:
console.log(employee.get("name"))In TypeORM you simply do:
console.log(employee.name)To create an index in sequelize you do:
sequelize.define(
"user",
{},
{
indexes: [
{
unique: true,
fields: ["firstName", "lastName"],
},
],
},
)In TypeORM you do:
@Entity()
@Index(["firstName", "lastName"], { unique: true })
export class User {}Learn more about Indexes