Defining Entities
There are two ways how you can define your entities:
- Decorated classes
EntitySchema
helper
#
EntitySchema helperWith EntitySchema
helper you define the schema programmatically.
When creating new entity instances, you will need to use em.create()
method that will
create instance of internally created class.
You can optionally use custom class for entity instances. Read more about this approach in Defining Entities via EntitySchema section.
#
Classes and DecoratorsEntities are simple javascript objects (so called POJO), decorated with @Entity
decorator.
No real restrictions are made, you do not have to extend any base class, you are more than welcome
to use entity constructors, just do not forget to specify primary key with
@PrimaryKey
decorator.
As you can see, entity properties are decorated either with @Property
decorator, or with one
of reference decorators: @ManyToOne
, @OneToMany
, @OneToOne
and @ManyToMany
.
From v3 you can also use default exports when defining your entity.
Here is another example of Author
entity, that was referenced from the Book
one, this
time defined for mongo:
More information about modelling relationships can be found on modelling relationships page.
If you want to define your entity in Vanilla JavaScript, take a look here.
#
Optional PropertiesWhen you define the property as optional (marked with ?
), this will be automatically considered
as nullable property (mainly for SQL schema generator).
This auto-detection works only when you omit the
type
/entity
attribute.
#
Default valuesYou can set default value of a property in 2 ways:
Use runtime default value of the property. This approach should be preferred as long as you are not using any native database function like
now()
. With this approach your entities will have the default value set even before it is actually persisted into the database (e.g. when you instantiate new entity vianew Author()
orem.create(Author, { ... })
.Use
default
parameter of@Property
decorator. This way the actual default value will be provided by the database, and automatically mapped to the entity property after it is being persisted (after flush). To use SQL functions likenow()
, usedefaultRaw
.Since v4 you should use
defaultRaw
for SQL functions, asdefault
with string values will be automatically quoted.
#
EnumsTo define enum property, use @Enum()
decorator. Enums can be either numeric or string valued.
For schema generator to work properly in case of string enums, you need to define the enum is same file as where it is used, so its values can be automatically discovered. If you want to define the enum in another file, you should reexport it also in place where you use it.
Another possibility is to provide the reference to the enum implementation in the decorator
via @Enum(() => UserRole)
.
You can also set enum items manually via
items: string[]
attribute.
#
Formulas@Formula()
decorator can be used to map some SQL snippet to your entity.
The SQL fragment can be as complex as you want and even include subselects.
Formulas will be added to the select clause automatically. In case you are facing
problems with NonUniqueFieldNameException
, you can define the formula as a
callback that will receive the entity alias in the parameter:
#
IndexesYou can define indexes via @Index()
decorator, for unique indexes, use @Unique()
decorator.
You can use it either on entity class, or on entity property:
#
Custom TypesYou can define custom types by extending Type
abstract class. It has 4 optional methods:
convertToDatabaseValue(value: any, platform: Platform): any
Converts a value from its JS representation to its database representation of this type.
convertToJSValue(value: any, platform: Platform): any
Converts a value from its database representation to its JS representation of this type.
toJSON(value: any, platform: Platform): any
Converts a value from its JS representation to its serialized JSON form of this type. By default converts to the database value.
getColumnType(prop: EntityProperty, platform: Platform): string
Gets the SQL declaration snippet for a field of this type.
More information can be found in Custom Types section.
#
Lazy scalar propertiesYou can mark any property as lazy: true
to omit it from the select clause.
This can be handy for properties that are too large and you want to have them
available only some times, like a full text of an article.
You can use populate
parameter to load them.
If the entity is already loaded and you need to populate a lazy scalar property, you might need to pass
refresh: true
in theFindOptions
.
#
Virtual PropertiesYou can define your properties as virtual, either as a method, or via JavaScript get/set
.
Following example defines User entity with firstName
and lastName
database fields, that
are both hidden from the serialized response, replaced with virtual properties fullName
(defined as a classic method) and fullName2
(defined as a JavaScript getter).
For JavaScript getter you need to provide
{ persist: false }
option otherwise the value would be stored in the database.
#
Entity file namesThis limitation applies only to folder based discovery. Another way around it is using
EntitySchema
for entity definition.
You are free to choose one of those formats for entity filename (for a BookTag
entity):
BookTag.ts
BookTag.model.ts
book-tag.ts
book-tag.model.ts
book-tag.entity.ts
Entity name is inferred from the first part of file name before first dot occurs, so you can
add any suffix behind the dot, not just .model.ts
or .entity.ts
.
You can change this behaviour by defining custom
NamingStrategy.getClassName()
method.
#
Using BaseEntityYou can define your own base entity with properties that you require on all entities, like primary key and created/updated time. Single table inheritance is also supported.
Read more about this topic in Inheritance Mapping section.
If you are initializing the ORM via
entities
option, you need to specify all your base entities as well.
#
Examples of entity definition with various primary keys#
Using id as primary key (SQL drivers)#
Using UUID as primary key (SQL drivers)uuid-osp module function as primary key#
Using PostgreSQLRequires enabling the module via: create extension "uuid-ossp";
#
Using BigInt as primary key (MySQL and PostgreSQL)You can use BigIntType
to support bigint
s. By default it will represent the value as
a string
.
If you want to use native bigint
s, read the following guide: Using native BigInt PKs.
#
Example of Mongo entity#
Using BaseEntity (previously WrappedEntity)From v4 BaseEntity
class is provided with init
, isInitialized
, assign
and other methods that are otherwise available via the wrap()
helper.
Usage of
BaseEntity
is optional.
With your entities set up, you can start using entity manager and repositories as described in following sections.