Separating Entity Definition

Defining Schemas

You can define an entity and its columns right in the model, using decorators. But some people prefer to define an entity and its columns inside separate files which are called "entity schemas" in TypeORM.
Simple definition example:
1
import {EntitySchema} from "typeorm";
2
3
export const CategoryEntity = new EntitySchema({
4
name: "category",
5
columns: {
6
id: {
7
type: Number,
8
primary: true,
9
generated: true
10
},
11
name: {
12
type: String
13
}
14
}
15
});
Copied!
Example with relations:
1
import {EntitySchema} from "typeorm";
2
3
export const PostEntity = new EntitySchema({
4
name: "post",
5
columns: {
6
id: {
7
type: Number,
8
primary: true,
9
generated: true
10
},
11
title: {
12
type: String
13
},
14
text: {
15
type: String
16
}
17
},
18
relations: {
19
categories: {
20
type: "many-to-many",
21
target: "category" // CategoryEntity
22
}
23
}
24
});
Copied!
Complex example:
1
import {EntitySchema} from "typeorm";
2
3
export const PersonSchema = new EntitySchema({
4
name: "person",
5
columns: {
6
id: {
7
primary: true,
8
type: "int",
9
generated: "increment"
10
},
11
firstName: {
12
type: String,
13
length: 30
14
},
15
lastName: {
16
type: String,
17
length: 50,
18
nullable: false
19
},
20
age: {
21
type: Number,
22
nullable: false
23
}
24
},
25
checks: [
26
{ expression: `"firstName" <> 'John' AND "lastName" <> 'Doe'` },
27
{ expression: `"age" > 18` }
28
],
29
indices: [
30
{
31
name: "IDX_TEST",
32
unique: true,
33
columns: [
34
"firstName",
35
"lastName"
36
]
37
}
38
],
39
uniques: [
40
{
41
name: "UNIQUE_TEST",
42
columns: [
43
"firstName",
44
"lastName"
45
]
46
}
47
]
48
});
Copied!
If you want to make your entity typesafe, you can define a model and specify it in schema definition:
1
import {EntitySchema} from "typeorm";
2
3
export interface Category {
4
id: number;
5
name: string;
6
}
7
8
export const CategoryEntity = new EntitySchema<Category>({
9
name: "category",
10
columns: {
11
id: {
12
type: Number,
13
primary: true,
14
generated: true
15
},
16
name: {
17
type: String
18
}
19
}
20
});
Copied!

Extending Schemas

When using the Decorator approach it is easy to extend basic columns to an abstract class and simply extend this. For example, your id, createdAt and updatedAt columns may be defined in such a BaseEntity. For more details, see the documentation on concrete table inheritance.
When using the EntitySchema approach, this is not possible. However, you can use the Spread Operator (...) to your advantage.
Reconsider the Category example from above. You may want to extract basic column descriptions and reuse it across your other schemas. This may be done in the following way:
1
import {EntitySchemaColumnOptions} from "typeorm";
2
3
export const BaseColumnSchemaPart = {
4
id: {
5
type: Number,
6
primary: true,
7
generated: true,
8
} as EntitySchemaColumnOptions,
9
createdAt: {
10
name: 'created_at',
11
type: 'timestamp with time zone',
12
createDate: true,
13
} as EntitySchemaColumnOptions,
14
updatedAt: {
15
name: 'updated_at',
16
type: 'timestamp with time zone',
17
updateDate: true,
18
} as EntitySchemaColumnOptions,
19
};
Copied!
Now you can use the BaseColumnSchemaPart in your other schema models, like this:
1
export const CategoryEntity = new EntitySchema<Category>({
2
name: "category",
3
columns: {
4
...BaseColumnSchemaPart,
5
// the CategoryEntity now has the defined id, createdAt, updatedAt columns!
6
// in addition, the following NEW fields are defined
7
name: {
8
type: String
9
}
10
}
11
});
Copied!
Be sure to add the extended columns also to the Category interface (e.g., via export interface Category extend BaseEntity).

Using Schemas to Query / Insert Data

Of course, you can use the defined schemas in your repositories or entity manager as you would use the decorators. Consider the previously defined Category example (with its Interface and CategoryEntity schema in order to get some data or manipulate the database.
1
// request data
2
const categoryRepository = getRepository<Category>(CategoryEntity);
3
const category = await categoryRepository.findOne(1); // category is properly typed!
4
5
// insert a new category into the database
6
const categoryDTO = {
7
// note that the ID is autogenerated; see the schema above
8
name: 'new category',
9
};
10
const newCategory = await categoryRepository.save(categoryDTO);
Copied!