Entity References
Every single entity relation is mapped to an entity reference. Reference is an entity that has only its identifier. This reference is stored in identity map so you will get the same object reference when fetching the same document from database.
You can call await entity.init()
to initialize the entity. This will trigger database call
and populate itself, keeping the same reference in identity map.
Reference<T>
Wrapper#
Better Type-safety with When you define @ManyToOne
and @OneToOne
properties on your entity, TypeScript compiler
will think that desired entities are always loaded:
You can overcome this issue by using the Reference<T>
wrapper. It simply wraps the entity,
defining load(): Promise<T>
method that will first lazy load the association if not already
available. You can also use unwrap(): T
method to access the underlying entity without loading
it.
You can also use get<K extends keyof T>(prop: K): Promise<T[K]>
helper, that will call load()
for you, making sure the entity is initialized first, then returning the value of given property
directly.
There are also getEntity()
and getProperty()
methods that are synchronous getters,
that will first check if the wrapped entity is initialized, and if not, it will throw
and error.
If you use different metadata provider than TsMorphMetadataProvider
(e.g. ReflectMetadataProvider
), you will also need to explicitly set wrappedReference
parameter:
#
Assigning to Reference PropertiesWhen you define the property as Reference
wrapper, you will need to assign the Reference
to it instead of the entity. You can create it via Reference.create()
factory, or use wrapped
parameter of em.getReference()
:
Another way is to use toReference()
method available as part of
WrappedEntity
interface:
If the reference already exist, you can also re-assign to it via set()
method:
#
What is IdentifiedReference?IdentifiedReference
is an intersection type that adds primary key property to the Reference
interface. It allows to get the primary key from Reference
instance directly.
By default it defines the PK property as id
, you can override this via second generic type
argument.
You can also have non-standard primary key like uuid
:
For MongoDB, defined the PK generic type argument as 'id' | '_id'
to access both string
and ObjectId
PK values:
As opposed to
Entity.init()
which always refreshes the entity,Reference.load()
method will query the database only if the entity is not already loaded in Identity Map.