Skip to main content
Version: Next

Options <Driver, EM, Entities>

MikroORM configuration options.

@see

Hierarchy

Index

Properties

optionalallowGlobalContext

allowGlobalContext?: boolean = false

Allow using the global EntityManager without a request context. Not recommended for production - each request should have its own context. Can also be set via MIKRO_ORM_ALLOW_GLOBAL_CONTEXT environment variable.

optionalassign

assign?: AssignOptions<boolean>

Default options for entity assignment via em.assign().

@see

optionalautoJoinOneToOneOwner

autoJoinOneToOneOwner?: boolean = true

Automatically join the owning side of 1:1 relations when querying the inverse side.

optionalautoJoinRefsForFilters

autoJoinRefsForFilters?: boolean = true

Automatically join M:1 and 1:1 relations when filters are defined on them. Important for implementing soft deletes via filters.

optionalbaseDir

baseDir?: string = process.cwd()

Base directory for resolving relative paths.

optionalbatchSize

batchSize?: number = 300

Number of entities to process in each batch for batch inserts/updates.

optionalinheritedcharset

charset?: string

Character set for the connection.

optionalinheritedclientUrl

clientUrl?: string

Full client connection URL. Overrides individual connection options.

optionalinheritedcollate

collate?: string

Collation for the connection.

optionalcolors

colors?: boolean = true

Enable colored output in logs.

optionalcontext

context?: (name) => undefined | EntityManager<IDatabaseDriver<Connection>> = (name) => undefined | EntityManager<IDatabaseDriver<Connection>>

Callback to get the current request context's EntityManager. Used for automatic context propagation in web frameworks.


Type declaration

optionalcontextName

contextName?: string = ‘default’

Name of the context for multi-ORM setups.

optionaldataloader

dataloader?: boolean | DataloaderType = boolean | DataloaderType

Enable dataloader for batching reference loading.

  • true or DataloaderType.ALL: Enable for all relation types
  • false or DataloaderType.NONE: Disable dataloader
  • DataloaderType.REFERENCE: Enable only for scalar references
  • DataloaderType.COLLECTION: Enable only for collections

optionalinheriteddbName

dbName?: string

Name of the database to connect to.

optionaldebug

debug?: boolean | LoggerNamespace[] = boolean | LoggerNamespace[]

Enable debug logging. Can be true for all namespaces or an array of specific namespaces. Available namespaces: 'query', 'query-params', 'discovery', 'info'.

@see

optionaldisableIdentityMap

disableIdentityMap?: boolean = false

Disable the identity map. When disabled, each query returns new entity instances. Not recommended for most use cases.

optionaldisableTransactions

disableTransactions?: boolean = false

Disable all transactions. When enabled, no queries will be wrapped in transactions, even when explicitly requested.

optionaldiscovery

Metadata discovery configuration options. Controls how entities are discovered and validated.

optionaldriver

driver?: new (config) => Driver

Database driver class to use. Should be imported from the specific driver package (e.g. @mikro-orm/mysql, @mikro-orm/postgresql). Alternatively, use the defineConfig helper or MikroORM class exported from the driver package.

@example
import { MySqlDriver } from '@mikro-orm/mysql';

MikroORM.init({
driver: MySqlDriver,
dbName: 'my_db',
});

Type declaration

optionalinheriteddriverOptions

driverOptions?: Dictionary

Additional driver-specific options. The object will be deeply merged with internal driver options.

optionaldynamicImportProvider

dynamicImportProvider?: (id) => Promise<unknown> = (id) => Promise<unknown>

Custom dynamic import provider for loading modules.


Type declaration

    • (id): Promise<unknown>
    • Parameters

      • id: string

      Returns Promise<unknown>

optionalembeddables

embeddables?: { prefixMode: EmbeddedPrefixMode }

Embeddable entity configuration options.


Type declaration

  • prefixMode: EmbeddedPrefixMode

    Mode for generating column prefixes for embedded properties.

optionalensureDatabase

ensureDatabase?: boolean | EnsureDatabaseOptions = boolean | EnsureDatabaseOptions

Ensure the database exists when initializing the ORM. When true, will create the database if it doesn't exist.

optionalensureIndexes

ensureIndexes?: boolean = false

Ensure database indexes exist on startup. This option works only with the MongoDB driver. When enabled, indexes will be created based on entity metadata.

optionalentities

entities?: Entities

Array of entity classes or paths to entity modules. Paths support glob patterns for automatic discovery.

@example
entities: [Author, Book, Publisher] // class references
entities: ['./dist/entities'] // folder paths

optionalentitiesTs

entitiesTs?: Entities

Array of TypeScript entity source paths. Used when running in TypeScript mode (e.g., via tsx or swc). Should always be specified when using folder-based discovery.

@example
entitiesTs: ['./src/entities']

optionalentityGenerator

entityGenerator?: GenerateOptions

Entity generator (code generation) configuration options.

@see

optionalentityManager

entityManager?: Constructor<EM>

Custom entity manager class to use.

optionalentityRepository

entityRepository?: EntityClass<EntityRepository<any>>

Custom base repository class for all entities. Entity-specific repositories can still be defined and will take precedence.

@see

optionalextensions

extensions?: { register: (orm) => void }[]

ORM extensions to register (e.g., Migrator, EntityGenerator, SeedManager). Extensions registered here are available via shortcuts like orm.migrator.

@example
extensions: [Migrator, EntityGenerator, SeedManager]

optionalfilters

filters?: Dictionary<{ name?: string } & Omit<FilterDef, name>>

Global entity filters to apply. Filters are applied by default unless explicitly disabled.

@see

optionalfiltersOnRelations

filtersOnRelations?: boolean = true

Apply filters to relations in queries.

optionalfindExactlyOneOrFailHandler

findExactlyOneOrFailHandler?: (entityName, where) => Error

Custom error handler for em.findExactlyOneOrFail() when entity count is not exactly one. Used when strict mode is enabled.


Type declaration

    • (entityName, where): Error

    • Parameters

      • entityName: string

        Name of the entity being queried

      • where: Dictionary | IPrimaryKeyValue

        Query conditions

      Returns Error

      Error instance to throw

optionalfindOneOrFailHandler

findOneOrFailHandler?: (entityName, where) => Error

Custom error handler for em.findOneOrFail() when no entity is found.


Type declaration

    • (entityName, where): Error

    • Parameters

      • entityName: string

        Name of the entity being queried

      • where: Dictionary | IPrimaryKeyValue

        Query conditions

      Returns Error

      Error instance to throw

optionalflushMode

flushMode?: always | FlushMode | commit | auto = always | FlushMode | commit | auto

Default flush mode for the entity manager.

  • 'commit': Flush only on explicit commit
  • 'auto': Flush before queries when needed
  • 'always': Always flush before queries

optionalforceEntityConstructor

forceEntityConstructor?: boolean | (string | Constructor<Partial<any>>)[] = boolean | (string | Constructor<Partial<any>>)[]

Force use of entity constructors when creating entity instances. Required when using native private properties inside entities. Can be true for all entities or an array of specific entity classes/names.

optionalforceUndefined

forceUndefined?: boolean = false

Convert null values from database to undefined when hydrating entities.

optionalforceUtcTimezone

forceUtcTimezone?: boolean = true

Force Date values to be stored in UTC for datetime columns without timezone. Works for MySQL (datetime type), PostgreSQL (timestamp type), and MSSQL (datetime/datetime2 types). SQLite does this by default.

optionalhighlighter

highlighter?: Highlighter = Highlighter

Syntax highlighter for SQL queries in logs.

optionalinheritedhost

host?: string

Database server hostname.

optionalhydrator

hydrator?: HydratorConstructor = HydratorConstructor

Custom hydrator class for assigning database values to entities.

optionalignoreDeprecations

ignoreDeprecations?: boolean | string[] = boolean | string[]

Ignore deprecation warnings. Can be true to ignore all or an array of specific deprecation labels.

@see

optionalignoreUndefinedInQuery

ignoreUndefinedInQuery?: boolean = false

Ignore undefined values in find queries instead of treating them as null.

@example
// With ignoreUndefinedInQuery: true
em.find(User, { email: undefined }) // resolves to em.find(User, {})

optionalimplicitTransactions

implicitTransactions?: boolean

Enable implicit transactions for all write operations. When enabled, all queries will be wrapped in a transaction. Disabled for MongoDB driver by default.

optionalloadStrategy

loadStrategy?: LoadStrategy | select-in | joined | balanced = LoadStrategy | select-in | joined | balanced

Default loading strategy for relations.

  • 'joined': Use SQL JOINs (single query, may cause cartesian product)
  • 'select-in': Use separate SELECT IN queries (multiple queries)
  • 'balanced': Decides based on relation type and context.

optionallogger

logger?: (message) => void = (message) => void

Custom logger function for ORM output.


Type declaration

    • (message): void
    • Parameters

      • message: string

      Returns void

optionalloggerFactory

loggerFactory?: (options) => Logger = (options) => Logger

Factory function to create a custom logger instance.


Type declaration

optionalmetadataCache

metadataCache?: { adapter?: new (...params) => SyncCacheAdapter; combined?: string | boolean; enabled?: boolean; options?: Dictionary; pretty?: boolean }

Metadata cache configuration for improved startup performance.

@see

Type declaration

  • optionaladapter?: new (...params) => SyncCacheAdapter

    Cache adapter class to use. When cache is enabled, and no adapter is provided explicitly, FileCacheAdapter is used automatically - but only if you use the async MikroORM.init() method.

  • optionalcombined?: string | boolean

    Combine all metadata into a single cache file. Can be true for default path or a custom path string.

  • optionalenabled?: boolean

    Enable metadata caching. Defaults based on the metadata provider's useCache() method.

  • optionaloptions?: Dictionary

    Options passed to the cache adapter constructor.

  • optionalpretty?: boolean

    Pretty print JSON cache files.

optionalmetadataProvider

metadataProvider?: { useCache?: () => boolean } = { useCache?: () => boolean }

Metadata provider class for entity discovery. Built-in options: ReflectMetadataProvider (default), TsMorphMetadataProvider.

@see

Type declaration

optionalmigrations

migrations?: MigrationsOptions

Migration configuration options.

@see

optionalinheritedmultipleStatements

multipleStatements?: boolean = false

Enable multiple statements in a single query. Required for importing database dump files. Should be disabled in production for security.

optionalinheritedname

name?: string

Name of the connection (used for logging when replicas are used).

optionalnamingStrategy

namingStrategy?: new () => NamingStrategy

Custom naming strategy class for mapping entity/property names to database table/column names. Built-in options: UnderscoreNamingStrategy, MongoNamingStrategy, EntityCaseNamingStrategy.

@see

Type declaration

optionalinheritedonCreateConnection

onCreateConnection?: (connection) => Promise<void>

Callback to execute when a new connection is created.


Type declaration

    • (connection): Promise<void>
    • Parameters

      • connection: unknown

      Returns Promise<void>

optionalonQuery

onQuery?: (sql, params) => string

Hook to modify SQL queries before execution. Useful for adding observability hints or query modifications.


Type declaration

    • (sql, params): string

    • Parameters

      • sql: string

        The generated SQL query

      • params: readonly unknown[]

        Query parameters

      Returns string

      Modified SQL query

optionalinheritedpassword

password?: string | () => MaybePromise<string>

Database password. Can be a string or a callback function that returns the password. The callback is useful for short-lived tokens from cloud providers.

@example
password: async () => someCallToGetTheToken()

optionalpersistOnCreate

persistOnCreate?: boolean = true

Automatically call em.persist() on entities created via em.create().

optionalinheritedpool

pool?: PoolConfig

Connection pool configuration.

optionalpopulateAfterFlush

populateAfterFlush?: boolean = true

Mark all relations as populated after flush for new entities. This aligns serialized output of loaded entities and just-inserted ones.

optionalpopulateWhere

populateWhere?: PopulateHint | infer | all = PopulateHint | infer | all

Determines how where conditions are applied during population.

  • 'all': Populate all matching relations (default in v5+)
  • 'infer': Infer conditions from the original query (v4 behavior)

optionalinheritedport

port?: number

Database server port number.

optionalpreferReadReplicas

preferReadReplicas?: boolean = true

Prefer read replicas for read operations when available.

optionalpreferTs

preferTs?: boolean = false

Force the ORM to use TypeScript options regardless of detection. Uses entitiesTs for discovery and pathTs for migrations/seeders. Should only be used for tests, not production builds.

optionalprocessOnCreateHooksEarly

processOnCreateHooksEarly?: boolean = true

Property onCreate hooks are normally executed during flush operation. With this option, they will be processed early inside em.create() method.

optionalpropagationOnPrototype

propagationOnPrototype?: boolean = true

Enable propagation of changes on entity prototypes.

optionalreplicas

replicas?: ConnectionOptions[]

Read replica connection configurations. Each replica can override parts of the main connection options.

@see

optionalresultCache

resultCache?: { adapter?: new (...params) => CacheAdapter; expiration?: number; global?: number | boolean | [string, number]; options?: Dictionary }

Result cache configuration for query result caching.


Type declaration

  • optionaladapter?: new (...params) => CacheAdapter

    Cache adapter class to use.

  • optionalexpiration?: number

    Default cache expiration time in milliseconds.

  • optionalglobal?: number | boolean | [string, number]

    Enable global result caching for all queries. Can be true, an expiration number, or a tuple of [key, expiration].

  • optionaloptions?: Dictionary

    Options passed to the cache adapter constructor.

optionalinheritedschema

schema?: string

Default database schema to use.

optionalschemaGenerator

schemaGenerator?: { createForeignKeyConstraints?: boolean; disableForeignKeys?: boolean; ignoreSchema?: string[]; managementDbName?: string; skipColumns?: Dictionary<(string | RegExp)[]>; skipTables?: (string | RegExp)[] }

Schema generator configuration options.


Type declaration

  • optionalcreateForeignKeyConstraints?: boolean

    Generate foreign key constraints.

  • optionaldisableForeignKeys?: boolean

    Try to disable foreign key checks during schema operations.

  • optionalignoreSchema?: string[]

    Schema names to ignore when comparing schemas.

  • optionalmanagementDbName?: string

    Database name to use for management operations (e.g., creating/dropping databases).

  • optionalskipColumns?: Dictionary<(string | RegExp)[]>

    Column names or patterns to skip during schema generation, keyed by table name.

  • optionalskipTables?: (string | RegExp)[]

    Table names or patterns to skip during schema generation.

optionalseeder

seeder?: SeederOptions

Seeder configuration options.

@see

optionalserialization

serialization?: { forceObject?: boolean; includePrimaryKeys?: boolean }

Serialization options for toJSON() and serialize() methods.


Type declaration

  • optionalforceObject?: boolean

    Enforce unpopulated references to be returned as objects. When enabled, references are serialized as { author: { id: 1 } } instead of { author: 1 }.

  • optionalincludePrimaryKeys?: boolean

    Include primary keys in serialized output.

optionalsubscribers

subscribers?: Iterable<EventSubscriber<any> | Constructor<EventSubscriber<any>>, any, any>

Event subscribers to register. Can be class references or instances.

optionaltimezone

timezone?: string

Timezone to use for date operations.

@example
'+02:00'

optionalupsertManaged

upsertManaged?: boolean = true

When upsert creates a new entity, mark it as managed in the identity map.

optionaluseBatchInserts

useBatchInserts?: boolean = true

Use batch insert queries for better performance.

optionaluseBatchUpdates

useBatchUpdates?: boolean = true

Use batch update queries for better performance.

optionalinheriteduser

user?: string

Database user name.

optionalvalidateRequired

validateRequired?: boolean = true

Validate that required properties are set on new entities before insert.

optionalverbose

verbose?: boolean = false

Enable verbose logging of internal operations.