# Entity mapping

We can return to the <mark style="color:purple;">user.entity</mark> file, where we'll map our entity to the database by using **TypeORM decorators**.

Begin by marking the class itself with <mark style="color:blue;">`@Entity()`</mark>, indicating that it should be a table. After that, we can mark the <mark style="color:blue;">`id`</mark> attribute with <mark style="color:blue;">`@PrimaryGeneratedColumn()`</mark>, indicating that it is the **primary column** and also **serial** (auto-increment). Finally, we can mark the remaining attributes with <mark style="color:blue;">`@Column()`</mark> to indicate that they are normal columns. As they are all of type <mark style="color:blue;">`string`</mark>, they will, by default, be mapped to VARCHAR.

Finally, let's also create an options object inside the <mark style="color:blue;">`@Column()`</mark> decorator over the <mark style="color:blue;">`email`</mark> and <mark style="color:blue;">`phone`</mark> attributes to enable the <mark style="color:blue;">`unique`</mark> option, as every user should have a unique email and phone. Our current result should look like this:

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

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;

  @Column({ unique: true })
  phone: string;

  @Column()
  password: string;
}
```

We'll also create <mark style="color:blue;">`Date`</mark> columns to register when an entity was created or last updated. As this will be a recurring pattern, we'll use an **embedded entity** to represent this data and avoid repetition. So, let's create the file <mark style="color:purple;">common</mark>/<mark style="color:purple;">embedded</mark>/<mark style="color:purple;">registry-dates.embedded</mark> with the following:

```typescript
export class RegistryDates {
  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}
```

Finally, we can apply it in our <mark style="color:blue;">`User`</mark> class as an embedded entity.

```typescript
@Column(() => RegistryDates, { prefix: false })
registryDates: RegistryDates;
```

{% hint style="info" %}
Disabling the <mark style="color:blue;">`prefix`</mark> option prevents altering the fields' names when fetching.
{% endhint %}

<mark style="color:green;">**Commit**</mark> - Mapping user entity to database table
