Entity mapping
Let's map our user entity to a database table.
We can return to the user.entity file, where we'll map our entity to the database using TypeORM decorators.
Begin by marking the class itself with @Entity()
, indicating that it should be a table. After that, we can mark the id
attribute with @PrimaryGeneratedColumn()
, indicating that it is the primary column and also serial (auto-increment). Finally, we can mark the remaining attributes with @Column()
to indicate that they are normal columns. As they are all of type string
, they will by default be mapped to VARCHAR.
Finally, let's also create an options object inside the @Column()
decorator over the email
and phone
attributes to enable the unique
option, as every user should have a unique email and phone. Our current result should look like this:
We'll also create Date
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 common -> embedded -> registry-dates.embedded with the following:
Finally, we can apply it in our User
class as an embedded entity.
Disabling the prefix
option prevents altering the fields' names when fetching.
Commit - Mapping user entity to database table
Last updated