# 常见问题

> 英文标题：FAQ
> 官网原文：https://typeorm.io/docs/help/faq
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 58 块

---

<!-- EN -->
# FAQ

<!-- ZH -->
# 常见问题

<!-- EN -->
## How do I update a database schema?

<!-- ZH -->
## 如何更新数据库结构？

<!-- EN -->
One of the main responsibilities of TypeORM is to keep your database tables in sync with your entities. There are two ways that help you achieve this:

<!-- ZH -->
TypeORM 的主要职责之一就是让你的数据库表与实体保持同步。有两种方式可以帮你做到这一点：

<!-- EN -->
* Use `synchronize: true` in data source options:

<!-- ZH -->
* 在数据源选项中使用 `synchronize: true`：

<!-- EN -->
  ```typescript
import { DataSource } from "typeorm"

const myDataSource = new DataSource({
    // ...
    synchronize: true,
})
  ```

<!-- ZH -->
  ```typescript
import { DataSource } from "typeorm"

const myDataSource = new DataSource({
    // ...
    synchronize: true,
})
  ```

<!-- EN -->
  This option automatically syncs your database tables with the given entities each time you run this code. This option is perfect during development, but in production you may not want this option to be enabled.

<!-- ZH -->
  该选项会在你每次运行这段代码时，自动把数据库表与给定的实体同步。这个选项在开发阶段非常完美，但在生产环境中你可能不希望启用它。

<!-- EN -->
* Use command line tools and run schema sync manually in the command line:

<!-- ZH -->
* 使用命令行工具，在命令行中手动运行结构同步：

<!-- EN -->
  ```shell
typeorm schema:sync
  ```

<!-- ZH -->
  ```shell
typeorm schema:sync
  ```

<!-- EN -->
  This command will execute schema synchronization.

<!-- ZH -->
  该命令会执行结构同步。

<!-- EN -->
Schema sync is extremely fast. If you are considering to disable synchronize option during development because of performance issues, first check how fast it is.

<!-- ZH -->
结构同步非常快。如果你因为性能问题正考虑在开发阶段禁用 synchronize 选项，请先看看它到底有多快。

<!-- EN -->
## How do I change a column name in the database?

<!-- ZH -->
## 如何修改数据库中的列名？

<!-- EN -->
By default, column names are generated from property names. You can simply change it by specifying a `name` column option:

<!-- ZH -->
默认情况下，列名由属性名生成。你只需指定一个 `name` 列选项就能修改它：

<!-- EN -->
```typescript
@Column({ name: "is_active" })
isActive: boolean;
```

<!-- ZH -->
```typescript
@Column({ name: "is_active" })
isActive: boolean;
```

<!-- EN -->
## How can I set the default value to some function, for example `NOW()`?

<!-- ZH -->
## 如何把默认值设为某个函数，例如 `NOW()`？

<!-- EN -->
`default` column option supports a function. If you are passing a function which returns a string, it will use that string as a default value without escaping it. For example:

<!-- ZH -->
`default` 列选项支持函数。如果你传入一个返回字符串的函数，它会把这个字符串原样用作默认值而不做转义。例如：

<!-- EN -->
```typescript
@Column({ default: () => "NOW()" })
date: Date;
```

<!-- ZH -->
```typescript
@Column({ default: () => "NOW()" })
date: Date;
```

<!-- EN -->
## How to do validation?

<!-- ZH -->
## 如何做校验？

<!-- EN -->
Validation is not part of TypeORM because validation is a separate process not really related to what TypeORM does. If you want to use validation use [class-validator](https://github.com/pleerock/class-validator) - it works perfectly with TypeORM.

<!-- ZH -->
校验不是 TypeORM 的一部分，因为校验是一个独立的过程，与 TypeORM 所做的事情并没有真正的关联。如果你想使用校验，请使用 [class-validator](https://github.com/pleerock/class-validator)——它与 TypeORM 配合得非常好。

<!-- EN -->
## What does "owner side" in a relations mean or why we need to use `@JoinColumn` and `@JoinTable`?

<!-- ZH -->
## 关系中的"拥有方"是什么意思，为什么需要使用 `@JoinColumn` 和 `@JoinTable`？

<!-- EN -->
Let's start with `one-to-one` relation. Let's say we have two entities: `User` and `Photo`:

<!-- ZH -->
我们从 `one-to-one` 关系说起。假设我们有两个实体：`User` 和 `Photo`：

<!-- EN -->
```typescript
@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToOne()
    photo: Photo
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToOne()
    photo: Photo
}
```

<!-- EN -->
```typescript
@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string

    @OneToOne()
    user: User
}
```

<!-- ZH -->
```typescript
@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string

    @OneToOne()
    user: User
}
```

<!-- EN -->
This example does not have a `@JoinColumn` which is incorrect. Why? Because to make a real relation, we need to create a column in the database. We need to create a column `userId` in `photo` or `photoId` in `user`. But which column should be created - `userId` or `photoId`? TypeORM cannot decide for you. To make a decision, you must use `@JoinColumn` on one of the sides. If you put `@JoinColumn` in `Photo` then a column called `userId` will be created in the `photo` table. If you put `@JoinColumn` in `User` then a column called `photoId` will be created in the `user` table. The side with `@JoinColumn` will be called the "owner side of the relationship". The other side of the relation, without `@JoinColumn`, is called the "inverse (non-owner) side of relationship".

<!-- ZH -->
这个示例没有 `@JoinColumn`，这是不正确的。为什么？因为要建立真正的关系，我们需要在数据库中创建一个列。我们需要在 `photo` 中创建一个 `userId` 列，或者在 `user` 中创建一个 `photoId` 列。但究竟该创建哪一列——`userId` 还是 `photoId`？TypeORM 无法替你决定。要做出决定，你必须在其中一侧使用 `@JoinColumn`。如果你把 `@JoinColumn` 放在 `Photo` 中，那么 `photo` 表中会创建一个名为 `userId` 的列。如果你把 `@JoinColumn` 放在 `User` 中，那么 `user` 表中会创建一个名为 `photoId` 的列。带 `@JoinColumn` 的那一侧被称为"关系的拥有方"。关系中没有 `@JoinColumn` 的另一侧被称为"关系的反向（非拥有）方"。

<!-- EN -->
It is the same in a `@ManyToMany` relation. You use `@JoinTable` to show the owner side of the relation.

<!-- ZH -->
在 `@ManyToMany` 关系中也是同样的道理。你用 `@JoinTable` 来标明关系的拥有方。

<!-- EN -->
In `@ManyToOne` or `@OneToMany` relations, `@JoinColumn` is not necessary because both decorators are different, and the table where you put the `@ManyToOne` decorator will have the relational column.

<!-- ZH -->
在 `@ManyToOne` 或 `@OneToMany` 关系中，`@JoinColumn` 不是必需的，因为这两个装饰器本身就不同，你放 `@ManyToOne` 装饰器的那张表会持有关系列。

<!-- EN -->
`@JoinColumn` and `@JoinTable` decorators can also be used to specify additional join column / junction table settings, like join column name or junction table name.

<!-- ZH -->
`@JoinColumn` 和 `@JoinTable` 装饰器还可以用来指定额外的连接列 / 中间表设置，比如连接列名或中间表名。

<!-- EN -->
## How do I add extra columns into many-to-many (junction) table?

<!-- ZH -->
## 如何给多对多（中间）表添加额外列？

<!-- EN -->
It's not possible to add extra columns into a table created by a many-to-many relation. You'll need to create a separate entity and bind it using two many-to-one relations with the target entities (the effect will be same as creating a many-to-many table), and add extra columns in there. You can read more about this in [Many-to-Many relations](https://typeorm.io/docs/relations/many-to-many-relations#many-to-many-relations-with-custom-properties).

<!-- ZH -->
无法给多对多关系所创建的表添加额外列。你需要创建一个单独的实体，并用两个指向目标实体的多对一关系把它绑定起来（效果等同于创建一张多对多表），然后在其中添加额外列。你可以在[多对多关系](https://typeorm.io/docs/relations/many-to-many-relations#many-to-many-relations-with-custom-properties)中阅读更多相关内容。

<!-- EN -->
## How to handle outDir TypeScript compiler option?

<!-- ZH -->
## 如何处理 TypeScript 编译器的 outDir 选项？

<!-- EN -->
When you are using the `outDir` compiler option, don't forget to copy assets and resources your app is using into the output directory. Otherwise, make sure to setup correct paths to those assets.

<!-- ZH -->
当你使用 `outDir` 编译器选项时，别忘了把应用用到的资源文件复制到输出目录中。否则，请确保为这些资源配置正确的路径。

<!-- EN -->
One important thing to know is that when you remove or move entities, the old entities are left untouched inside the output directory. For example, you create a `Post` entity and rename it to `Blog`, you no longer have `Post.ts` in your project. However, `Post.js` is left inside the output directory. Now, when TypeORM reads entities from your output directory, it sees two entities - `Post` and `Blog`. This may be a source of bugs. That's why when you remove and move entities with `outDir` enabled, it's strongly recommended to remove your output directory and recompile the project again.

<!-- ZH -->
需要知道的一件重要事情是：当你移除或移动实体时，旧实体仍会原封不动地留在输出目录中。例如，你创建了一个 `Post` 实体并把它改名为 `Blog`，你的项目中不再有 `Post.ts`。然而 `Post.js` 仍留在输出目录中。此时，当 TypeORM 从你的输出目录读取实体时，它会看到两个实体——`Post` 和 `Blog`。这可能成为 bug 的来源。因此，在启用 `outDir` 的情况下移除和移动实体时，强烈建议删除输出目录并重新编译项目。

<!-- EN -->
## How to use TypeORM with ts-node?

<!-- ZH -->
## 如何把 TypeORM 与 ts-node 一起使用？

<!-- EN -->
You can prevent compiling files each time using [ts-node](https://github.com/TypeStrong/ts-node). If you are using ts-node, you can specify `ts` entities inside data source options:

<!-- ZH -->
你可以用 [ts-node](https://github.com/TypeStrong/ts-node) 避免每次都编译文件。如果你使用 ts-node，可以在数据源选项中指定 `ts` 实体：

<!-- EN -->
```typescript
{
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
    subscribers: [__dirname + "/subscribers/**/*{.js,.ts}"]
}
```

<!-- ZH -->
```typescript
{
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
    subscribers: [__dirname + "/subscribers/**/*{.js,.ts}"]
}
```

<!-- EN -->
Also, if you are compiling js files into the same folder where your typescript files are, make sure to use the `outDir` compiler option to prevent [this issue](https://github.com/TypeStrong/ts-node/issues/432).

<!-- ZH -->
另外，如果你把 js 文件编译到与 typescript 文件相同的文件夹中，请务必使用 `outDir` 编译器选项以避免[这个问题](https://github.com/TypeStrong/ts-node/issues/432)。

<!-- EN -->
Also, if you want to use the ts-node CLI, you can execute TypeORM the following way:

<!-- ZH -->
另外，如果你想使用 ts-node CLI，可以按下面的方式执行 TypeORM：

<!-- EN -->
```shell
npx typeorm-ts-node-commonjs schema:sync
```

<!-- ZH -->
```shell
npx typeorm-ts-node-commonjs schema:sync
```

<!-- EN -->
For ESM projects use this instead:

<!-- ZH -->
对 ESM 项目请改用：

<!-- EN -->
```shell
npx typeorm-ts-node-esm schema:sync
```

<!-- ZH -->
```shell
npx typeorm-ts-node-esm schema:sync
```

<!-- EN -->
## How to use Webpack for the backend?

<!-- ZH -->
## 如何在后端使用 Webpack？

<!-- EN -->
Webpack produces warnings due to what it views as missing require statements -- require statements for all drivers supported by TypeORM. To suppress these warnings for unused drivers, you will need to edit your webpack config file.

<!-- ZH -->
Webpack 会产生警告，因为它认为缺少 require 语句——即针对 TypeORM 所支持的全部驱动的 require 语句。要抑制这些针对未使用驱动的警告，你需要编辑 webpack 配置文件。

<!-- EN -->
```javascript
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');

module.exports = {
    ...
    plugins: [
        // ignore the drivers you don't want. This is the complete list of all drivers -- remove the suppressions for drivers you want to use.
        new FilterWarningsPlugin({
            exclude: [/mongodb/, /mssql/, /mysql2/, /oracledb/, /pg/, /pg-native/, /pg-query-stream/, /react-native-sqlite-storage/, /redis/, /sql.js/, /typeorm-aurora-data-api-driver/]
        })
    ]
};
```

<!-- ZH -->
```javascript
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');

module.exports = {
    ...
    plugins: [
        // 忽略你不想要的驱动。这是所有驱动的完整列表——把你想用的驱动的抑制项删掉。
        new FilterWarningsPlugin({
            exclude: [/mongodb/, /mssql/, /mysql2/, /oracledb/, /pg/, /pg-native/, /pg-query-stream/, /react-native-sqlite-storage/, /redis/, /sql.js/, /typeorm-aurora-data-api-driver/]
        })
    ]
};
```

<!-- EN -->
### Bundling Migration Files

<!-- ZH -->
### 打包迁移文件

<!-- EN -->
By default Webpack tries to bundle everything into one file. This can be problematic when your project has migration files which are meant to be executed after bundled code is deployed to production. To make sure all your [migrations](https://typeorm.io/docs/migrations/why) can be recognized and executed by TypeORM, you may need to use "Object Syntax" for the `entry` configuration for the migration files only.

<!-- ZH -->
默认情况下 Webpack 会尝试把所有东西打包进一个文件。当你的项目有迁移文件、而这些文件需要在打包后的代码部署到生产环境之后再执行时，这可能会出问题。为了确保你所有的[迁移](https://typeorm.io/docs/migrations/why)都能被 TypeORM 识别和执行，你可能需要仅为迁移文件对 `entry` 配置使用"对象语法"。

<!-- EN -->
```javascript
const { globSync } = require("node:fs")
const path = require("node:path")

module.exports = {
    // ... your webpack configurations here...
    // Dynamically generate a `{ [name]: sourceFileName }` map for the `entry` option
    // change `src/db/migrations` to the relative path to your migrations folder
    entry: globSync(path.resolve("src/db/migrations/*.ts")).reduce(
        (entries, filename) => {
            const migrationName = path.basename(filename, ".ts")
            return Object.assign({}, entries, {
                [migrationName]: filename,
            })
        },
        {},
    ),
    resolve: {
        // assuming all your migration files are written in TypeScript
        extensions: [".ts"],
    },
    output: {
        // change `path` to where you want to put transpiled migration files.
        path: __dirname + "/dist/db/migrations",
        // this is important - we want UMD (Universal Module Definition) for migration files.
        libraryTarget: "umd",
        filename: "[name].js",
    },
}
```

<!-- ZH -->
```javascript
const { globSync } = require("node:fs")
const path = require("node:path")

module.exports = {
    // ... 你的 webpack 配置...
    // 为 `entry` 选项动态生成一个 `{ [name]: sourceFileName }` 映射
    // 把 `src/db/migrations` 改成你的迁移文件夹的相对路径
    entry: globSync(path.resolve("src/db/migrations/*.ts")).reduce(
        (entries, filename) => {
            const migrationName = path.basename(filename, ".ts")
            return Object.assign({}, entries, {
                [migrationName]: filename,
            })
        },
        {},
    ),
    resolve: {
        // 假设你的所有迁移文件都是用 TypeScript 写的
        extensions: [".ts"],
    },
    output: {
        // 把 `path` 改成你想放转译后迁移文件的位置。
        path: __dirname + "/dist/db/migrations",
        // 这很重要——我们希望迁移文件使用 UMD（通用模块定义）。
        libraryTarget: "umd",
        filename: "[name].js",
    },
}
```

<!-- EN -->
Also, since Webpack 4, when using `mode: 'production'`, files are optimized by default which includes mangling your code in order to minimize file sizes. This breaks the [migrations](https://typeorm.io/docs/migrations/why) because TypeORM relies on their names to determine which has already been executed. You may disable minimization completely by adding:

<!-- ZH -->
另外，从 Webpack 4 开始，使用 `mode: 'production'` 时文件默认会被优化，其中包括混淆你的代码以缩小文件体积。这会破坏[迁移](https://typeorm.io/docs/migrations/why)，因为 TypeORM 依赖它们的名字来判断哪些已经执行过。你可以通过加上以下配置完全禁用最小化：

<!-- EN -->
```javascript
module.exports = {
    // ... other Webpack configurations here
    optimization: {
        minimize: false,
    },
}
```

<!-- ZH -->
```javascript
module.exports = {
    // ... 其他 Webpack 配置
    optimization: {
        minimize: false,
    },
}
```

<!-- EN -->
Alternatively, if you are using the `UglifyJsPlugin`, you can tell it to not change class or function names like so:

<!-- ZH -->
或者，如果你使用 `UglifyJsPlugin`，可以像下面这样告诉它不要改动类名或函数名：

<!-- EN -->
```javascript
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")

module.exports = {
    // ... other Webpack configurations here
    optimization: {
        minimizer: [
            new UglifyJsPlugin({
                uglifyOptions: {
                    keep_classnames: true,
                    keep_fnames: true,
                },
            }),
        ],
    },
}
```

<!-- ZH -->
```javascript
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")

module.exports = {
    // ... 其他 Webpack 配置
    optimization: {
        minimizer: [
            new UglifyJsPlugin({
                uglifyOptions: {
                    keep_classnames: true,
                    keep_fnames: true,
                },
            }),
        ],
    },
}
```

<!-- EN -->
Lastly, make sure in your data source options, the transpiled migration files are included:

<!-- ZH -->
最后，请确保在你的数据源选项中包含了转译后的迁移文件：

<!-- EN -->
```javascript
// TypeORM Configurations
module.exports = {
    // ...
    migrations: [__dirname + "/migrations/**/*{.js,.ts}"],
}
```

<!-- ZH -->
```javascript
// TypeORM 配置
module.exports = {
    // ...
    migrations: [__dirname + "/migrations/**/*{.js,.ts}"],
}
```

<!-- EN -->
## How to use TypeORM in ESM projects?

<!-- ZH -->
## 如何在 ESM 项目中使用 TypeORM？

<!-- EN -->
Make sure to add `"type": "module"` in the `package.json` of your project so TypeORM will know to use `import( ... )` on files.

<!-- ZH -->
请务必在你的项目 `package.json` 中加上 `"type": "module"`，这样 TypeORM 才知道要对文件使用 `import( ... )`。

<!-- EN -->
To avoid circular dependency import issues use the `Relation` wrapper type for relation type definitions in entities:

<!-- ZH -->
为避免循环依赖导入问题，请在实体的关系类型定义上使用 `Relation` 包装类型：

<!-- EN -->
```typescript
@Entity()
export class User {
    @OneToOne(() => Profile, (profile) => profile.user)
    profile: Relation<Profile>
}
```

<!-- ZH -->
```typescript
@Entity()
export class User {
    @OneToOne(() => Profile, (profile) => profile.user)
    profile: Relation<Profile>
}
```

<!-- EN -->
Doing this prevents the type of the property from being saved in the transpiled code in the property metadata, preventing circular dependency issues.

<!-- ZH -->
这样做可以防止该属性的类型被保存到转译后代码的属性元数据中，从而避免循环依赖问题。

<!-- EN -->
Since the type of the column is already defined using the `@OneToOne` decorator, there's no use of the additional type metadata saved by TypeScript.

<!-- ZH -->
由于列的类型已经通过 `@OneToOne` 装饰器定义了，TypeScript 保存的额外类型元数据并没有用处。

<!-- EN -->
> Important: Do not use `Relation` on non-relation column types

<!-- ZH -->
> 重要：不要在非关系列类型上使用 `Relation`
