📜  typeorm enum postgres (1)

📅  最后修改于: 2023-12-03 15:35:23.947000             🧑  作者: Mango

TypeORM Enum in Postgres

TypeORM is an Object-Relational Mapping (ORM) tool that allows programmers to work with databases using TypeScript or JavaScript. It supports a variety of databases including Postgres. In this article, we will discuss the use of TypeORM Enum in Postgres databases.

What is an Enum in Postgres?

In Postgres, an Enum is a user-defined data type that consists of a set of predefined values. Enum data type is useful when there is a fixed set of possible values for a particular column. Postgres allows defining an Enum data type using a CREATE TYPE statement. Once defined, the Enum data type can be used in table definitions.

Using Enum in TypeORM

TypeORM provides a way to define Enum data type in the entity definition. To create an Enum data type, you need to specify the name of the Enum and a list of its values. Here is an example code snippet that defines an Enum data type for a gender column:

enum Gender {
  MALE = 'Male',
  FEMALE = 'Female',
  OTHER = 'Other',
}

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  ...

  @Column({
    type: 'enum',
    enum: Gender,
    default: Gender.OTHER,
  })
  gender: Gender;
}

In this example, the User entity has a gender column that is of Enum data type. The Enum names are mapped to the string values and are used in the database column. The default property sets a default value, which is OTHER in this case.

Conclusion

TypeORM provides a convenient way to work with Postgres databases using TypeScript or JavaScript. The Enum data type is useful when there are a fixed set of values for a particular column. We hope this article has helped you understand how to use TypeORM Enum in Postgres databases.