In TypeORM you have the possibility to set a unique flag in the column options, or to set column(s) to unique for the entity.
When would you use which, and what's the difference there?
@Unique(["firstName"])
https://typeorm.io/#/decorator-reference/unique
@Column({ unique: true })
firstName: string;
https://typeorm.io/#/decorator-reference/column
To create a unique constraint with TypeORM, we can use the unique parameter. If we want to use multiple columns for our unique constraint, we need to use the @Unique decorator. An important thing about the @Unique decorator is that we supply it with the field names, not the names of the columns.
@PrimaryGeneratedColumn() field is used to specify the primary column as well as to auto generate the column value in the database.
As written in the docs @Unique
can only be applied to entire entities, not to a single column. For readability, I prefer for simple constraints @Column({ unique: true })
because it sits just on top of the affected variable name.
Another advantage of the @Unique
syntax is the multi-column constraint ability. You can define multiple columns as one unique constraint: @Unique(["firstName", "secondName"])
. This is not possible with the @Column
decorator.
Finally, you can set a name for a particular constraint, when using @Unique
decorator. The following single column constraint definition is functional equal, except @Unique
sets a human readable name (Attention: @Unique
expects the entity variable field name, not the actual database column name):
@Unique('my_unique_constraint', ['firstName']) // make firstName unique
export class PersonEntity {
@Column({ unique: true }) // make firstName unique, too; decide which to chose
firstName: string;
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With