Skip to main content
Version: Next

EntityManager <Driver>

The EntityManager is the central access point to ORM functionality. It is a facade to all different ORM subsystems such as UnitOfWork, Query Language, and Repository API.

Hierarchy

Index

Properties

readonly_id

_id: number = ...

readonlyconfig

readonlyglobal

global: false = false

readonlyname

name: string

Accessors

id

  • get id(): number
  • Returns the ID of this EntityManager. Respects the context, so global EM will give you the contextual ID if executed inside request context handler.


    Returns number

schema

  • get schema(): undefined | string
  • set schema(schema: undefined | null | string): void
  • Returns the default schema of this EntityManager. Respects the context, so global EM will give you the contextual schema if executed inside request context handler.


    Returns undefined | string

  • Sets the default schema of this EntityManager. Respects the context, so global EM will set the contextual schema if executed inside request context handler.


    Parameters

    • schema: undefined | null | string

    Returns void

Methods

addFilter

assign

  • Shortcut for wrap(entity).assign(data, { em })


    Parameters

    Returns MergeSelected<Entity, Naked, keyof Data & string>

begin

  • Starts new transaction bound to this EntityManager. Use ctx parameter to provide the parent when nesting transactions.


    Parameters

    Returns Promise<void>

canPopulate

  • canPopulate(entityName: EntityName<Entity>, property: string): boolean
  • Checks whether given property can be populated on the entity.


    Parameters

    Returns boolean

clear

  • clear(): void
  • Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.


    Returns void

clearCache

  • clearCache(cacheKey: string): Promise<void>
  • Clears result cache for given cache key. If we want to be able to call this method, we need to set the cache key explicitly when storing the cache.

    // set the cache key to 'book-cache-key', with expiration of 60s
    const res = await em.find(Book, { ... }, { cache: ['book-cache-key', 60_000] });

    // clear the cache key by name
    await em.clearCache('book-cache-key');

    Parameters

    • cacheKey: string

    Returns Promise<void>

commit

  • commit(): Promise<void>
  • Commits the transaction bound to this EntityManager. Flushes before doing the actual commit query.


    Returns Promise<void>

count

  • Returns total number of entities matching your where query.


    Parameters

    Returns Promise<number>

create

  • Creates new instance of given entity and populates it with given data. The entity constructor will be used unless you provide { managed: true } in the options parameter. The constructor will be given parameters based on the defined constructor of the entity. If the constructor parameter matches a property name, its value will be extracted from data. If no matching property exists, the whole data parameter will be passed. This means we can also define constructor(data: Partial<T>) and em.create() will pass the data into it (unless we have a property named data too).

    The parameters are strictly checked, you need to provide all required properties. You can use OptionalProps symbol to omit some properties from this check without making them optional. Alternatively, use partial: true in the options to disable the strict checks for required properties. This option has no effect on runtime.

    The newly created entity will be automatically marked for persistence via em.persist unless you disable this behavior, either locally via persist: false option, or globally via persistOnCreate ORM config option.


    Parameters

    Returns Entity

find

  • Finds all entities matching your where query. You can pass additional options via the options parameter.


    Parameters

    Returns Promise<Loaded<Entity, Hint, Fields, Excludes>[]>

findAll

  • Finds all entities of given type, optionally matching the where condition provided in the options parameter.


    Parameters

    Returns Promise<Loaded<Entity, Hint, Fields, Excludes>[]>

findAndCount

  • Calls em.find() and em.count() with the same arguments (where applicable) and returns the results as tuple where the first element is the array of entities, and the second is the count.


    Parameters

    Returns Promise<[Loaded<Entity, Hint, Fields, Excludes>[], number]>

findByCursor

  • Calls em.find() and em.count() with the same arguments (where applicable) and returns the results as Cursor object. Supports before, after, first and last options while disallowing limit and offset. Explicit orderBy option is required.

    Use first and after for forward pagination, or last and before for backward pagination.

    • first and last are numbers and serve as an alternative to offset, those options are mutually exclusive, use only one at a time
    • before and after specify the previous cursor value, it can be one of the:
      • Cursor instance
      • opaque string provided by startCursor/endCursor properties
      • POJO/entity instance
    const currentCursor = await em.findByCursor(User, {}, {
    first: 10,
    after: previousCursor, // cursor instance
    orderBy: { id: 'desc' },
    });

    // to fetch next page
    const nextCursor = await em.findByCursor(User, {}, {
    first: 10,
    after: currentCursor.endCursor, // opaque string
    orderBy: { id: 'desc' },
    });

    // to fetch next page
    const nextCursor2 = await em.findByCursor(User, {}, {
    first: 10,
    after: { id: lastSeenId }, // entity-like POJO
    orderBy: { id: 'desc' },
    });

    The Cursor object provides the following interface:

    Cursor<User> {
    items: [
    User { ... },
    User { ... },
    User { ... },
    ],
    totalCount: 50,
    startCursor: 'WzRd',
    endCursor: 'WzZd',
    hasPrevPage: true,
    hasNextPage: true,
    }

    Parameters

    Returns Promise<Cursor<Entity, Hint, Fields, Excludes>>

findOne

  • Finds first entity matching your where query.


    Parameters

    Returns Promise<null | Loaded<Entity, Hint, Fields, Excludes>>

findOneOrFail

  • Finds first entity matching your where query. If nothing found, it will throw an error. If the strict option is specified and nothing is found or more than one matching entity is found, it will throw an error. You can override the factory for creating this method via options.failHandler locally or via Configuration.findOneOrFailHandler (findExactlyOneOrFailHandler when specifying strict) globally.


    Parameters

    Returns Promise<Loaded<Entity, Hint, Fields, Excludes>>

flush

  • flush(): Promise<void>
  • Flushes all changes to objects that have been queued up to now to the database. This effectively synchronizes the in-memory state of managed objects with the database.


    Returns Promise<void>

fork

  • Returns new EntityManager instance with its own identity map


    Parameters

    Returns this

getComparator

getConnection

  • getConnection(type?: ConnectionType): ReturnType<Driver[getConnection]>
  • Gets the Connection instance, by default returns write connection


    Parameters

    Returns ReturnType<Driver[getConnection]>

getDriver

  • getDriver(): Driver
  • Gets the Driver instance used by this EntityManager. Driver is singleton, for one MikroORM instance, only one driver is created.


    Returns Driver

getEntityFactory

  • Gets the EntityFactory used by the EntityManager.


    Returns EntityFactory

getEventManager

getFilterParams

  • getFilterParams(name: string): T
  • Returns filter parameters for given filter set in this context.


    Parameters

    • name: string

    Returns T

getHydrator

  • getHydrator(): IHydrator
  • Gets the Hydrator used by the EntityManager.


    Returns IHydrator

getLoggerContext

  • getLoggerContext(): T
  • Gets logger context for this entity manager.


    Returns T

getMetadata

getPlatform

  • getPlatform(): ReturnType<Driver[getPlatform]>
  • Gets the platform instance. Just like the driver, platform is singleton, one for a MikroORM instance.


    Returns ReturnType<Driver[getPlatform]>

getReference

  • getReference(entityName: EntityName<Entity>, id: Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity, options: Omit<GetReferenceOptions, wrapped> & { wrapped: true }): Ref<Entity>
  • getReference(entityName: EntityName<Entity>, id: (Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity) | (Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity)[]): Entity
  • getReference(entityName: EntityName<Entity>, id: Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity, options: Omit<GetReferenceOptions, wrapped> & { wrapped: false }): Entity
  • getReference(entityName: EntityName<Entity>, id: Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity, options?: GetReferenceOptions): Entity | Reference<Entity>
  • Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded


    Parameters

    • entityName: EntityName<Entity>
    • id: Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity
    • options: Omit<GetReferenceOptions, wrapped> & { wrapped: true }

    Returns Ref<Entity>

getRepository

  • Gets repository for given entity. You can pass either string name or entity class reference.


    Parameters

    Returns GetRepository<Entity, Repository>

getTransactionContext

  • getTransactionContext(): undefined | T
  • Gets the transaction context (driver dependent object used to make sure queries are executed on same connection).


    Returns undefined | T

getUnitOfWork

  • Gets the UnitOfWork used by the EntityManager to coordinate operations.


    Parameters

    • useContext: boolean = true

    Returns UnitOfWork

getValidator

insert

  • insert(entityNameOrEntity: Entity | EntityName<Entity>, data?: Entity | RequiredEntityData<Entity>, options?: NativeInsertUpdateOptions<Entity>): Promise<Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity>
  • Fires native insert query. Calling this has no side effects on the context (identity map).


    Parameters

    Returns Promise<Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity>

insertMany

  • insertMany(entityNameOrEntities: EntityName<Entity> | Entity[], data?: Entity[] | RequiredEntityData<Entity>[], options?: NativeInsertUpdateOptions<Entity>): Promise<(Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity)[]>
  • Fires native multi-insert query. Calling this has no side effects on the context (identity map).


    Parameters

    Returns Promise<(Entity extends { [PrimaryKeyProp]?: PK } ? PK extends keyof Entity<Entity> ? ReadonlyPrimary<UnwrapPrimary<Entity<Entity>[PK<PK>]>> : PK extends keyof Entity<Entity>[] ? ReadonlyPrimary<PrimaryPropToType<Entity<Entity>, PK<PK>>> : PK : Entity extends { _id?: PK } ? string | ReadonlyPrimary<PK> : Entity extends { uuid?: PK } ? ReadonlyPrimary<PK> : Entity extends { id?: PK } ? ReadonlyPrimary<PK> : Entity)[]>

isInTransaction

  • isInTransaction(): boolean
  • Checks whether this EntityManager is currently operating inside a database transaction.


    Returns boolean

lock

  • Runs your callback wrapped inside a database transaction.


    Parameters

    Returns Promise<void>

map

  • Maps raw database result to an entity and merges it to this EntityManager.


    Parameters

    Returns Entity

merge

  • Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities via second parameter. By default, it will return already loaded entities without modifying them.


    Parameters

    Returns Entity

nativeDelete

  • Fires native delete query. Calling this has no side effects on the context (identity map).


    Parameters

    Returns Promise<number>

nativeUpdate

persist

  • persist(entity: Entity | Reference<Entity> | Iterable<Entity | Reference<Entity>, any, any>): this
  • Tells the EntityManager to make an instance managed and persistent. The entity will be entered into the database at or before transaction commit or as a result of the flush operation.


    Parameters

    Returns this

persistAndFlush

  • persistAndFlush(entity: Partial<any> | Reference<Partial<any>> | Iterable<Partial<any> | Reference<Partial<any>>, any, any>): Promise<void>
  • Persists your entity immediately, flushing all not yet persisted changes to the database too. Equivalent to em.persist(e).flush().


    Parameters

    • entity: Partial<any> | Reference<Partial<any>> | Iterable<Partial<any> | Reference<Partial<any>>, any, any>

    Returns Promise<void>

populate

  • populate(entities: Entity, populate: false | AutoPath<Naked, Hint, ALL>[], options?: EntityLoaderOptions<Naked, Fields, Excludes>): Promise<Entity extends object[] ? MergeLoaded<ArrayElement<Entity<Entity>>, Naked, Hint, Fields, Excludes>[] : MergeLoaded<Entity, Naked, Hint, Fields, Excludes>>
  • Loads specified relations in batch. This will execute one query for each relation, that will populate it on all the specified entities.


    Parameters

    Returns Promise<Entity extends object[] ? MergeLoaded<ArrayElement<Entity<Entity>>, Naked, Hint, Fields, Excludes>[] : MergeLoaded<Entity, Naked, Hint, Fields, Excludes>>

refresh

  • refresh(entity: Entity, options?: FindOneOptions<Entity, Hint, Fields, Excludes>): Promise<null | MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true>>
  • Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer in database, the method returns null.


    Parameters

    • entity: Entity
    • options: FindOneOptions<Entity, Hint, Fields, Excludes> = {}

    Returns Promise<null | MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true>>

refreshOrFail

  • refreshOrFail(entity: Entity, options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes>): Promise<MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true>>
  • Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted. Returns the same entity instance (same object reference), but re-hydrated. If the entity is no longer in database, the method throws an error just like em.findOneOrFail() (and respects the same config options).


    Parameters

    Returns Promise<MergeLoaded<Entity, Naked, Hint, Fields, Excludes, true>>

remove

  • remove(entity: Entity | Reference<Entity> | Iterable<Entity | Reference<Entity>, any, any>): this
  • Marks entity for removal. A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.

    To remove entities by condition, use em.nativeDelete().


    Parameters

    Returns this

removeAndFlush

  • removeAndFlush(entity: Partial<any> | Reference<Partial<any>> | Iterable<Partial<any> | Reference<Partial<any>>, any, any>): Promise<void>
  • Removes an entity instance immediately, flushing all not yet persisted changes to the database too. Equivalent to em.remove(e).flush()


    Parameters

    • entity: Partial<any> | Reference<Partial<any>> | Iterable<Partial<any> | Reference<Partial<any>>, any, any>

    Returns Promise<void>

repo

resetTransactionContext

  • resetTransactionContext(): void
  • Resets the transaction context.


    Returns void

rollback

  • rollback(): Promise<void>
  • Rollbacks the transaction bound to this EntityManager.


    Returns Promise<void>

setFilterParams

  • setFilterParams(name: string, args: Dictionary): void
  • Sets filter parameter values globally inside context defined by this entity manager. If you want to set shared value for all contexts, be sure to use the root entity manager.


    Parameters

    Returns void

setFlushMode

  • Parameters

    Returns void

setLoggerContext

  • Sets logger context for this entity manager.


    Parameters

    Returns void

setTransactionContext

  • setTransactionContext(ctx: any): void
  • Sets the transaction context.


    Parameters

    • ctx: any

    Returns void

transactional

  • Runs your callback wrapped inside a database transaction.


    Parameters

    Returns Promise<T>

upsert

  • Creates or updates the entity, based on whether it is already present in the database. This method performs an insert on conflict merge query ensuring the database is in sync, returning a managed entity instance. The method accepts either entityName together with the entity data, or just entity instance.

    // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
    const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });

    The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where Author.email is a unique property:

    // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
    // select "id" from "author" where "email" = 'foo@bar.com'
    const author = await em.upsert(Author, { email: 'foo@bar.com', age: 33 });

    Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the data.

    If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit flush will be required for those changes to be persisted.


    Parameters

    Returns Promise<Entity>

upsertMany

  • Creates or updates the entity, based on whether it is already present in the database. This method performs an insert on conflict merge query ensuring the database is in sync, returning a managed entity instance. The method accepts either entityName together with the entity data, or just entity instance.

    // insert into "author" ("age", "email") values (33, 'foo@bar.com') on conflict ("email") do update set "age" = 41
    const authors = await em.upsertMany(Author, [{ email: 'foo@bar.com', age: 33 }, ...]);

    The entity data needs to contain either the primary key, or any other unique property. Let's consider the following example, where Author.email is a unique property:

    // insert into "author" ("age", "email") values (33, 'foo@bar.com'), (666, 'lol@lol.lol') on conflict ("email") do update set "age" = excluded."age"
    // select "id" from "author" where "email" = 'foo@bar.com'
    const author = await em.upsertMany(Author, [
    { email: 'foo@bar.com', age: 33 },
    { email: 'lol@lol.lol', age: 666 },
    ]);

    Depending on the driver support, this will either use a returning query, or a separate select query, to fetch the primary key if it's missing from the data.

    If the entity is already present in current context, there won't be any queries - instead, the entity data will be assigned and an explicit flush will be required for those changes to be persisted.


    Parameters

    Returns Promise<Entity[]>