Options <Driver, EM, Entities>
Hierarchy
- ConnectionOptions
- Options
Index
Properties
- allowGlobalContext
- assign
- autoJoinOneToOneOwner
- autoJoinRefsForFilters
- baseDir
- batchSize
- charset
- clientUrl
- collate
- colors
- context
- contextName
- dataloader
- dbName
- debug
- disableIdentityMap
- disableTransactions
- discovery
- driver
- driverOptions
- dynamicImportProvider
- embeddables
- ensureDatabase
- ensureIndexes
- entities
- entitiesTs
- entityGenerator
- entityManager
- entityRepository
- extensions
- filters
- filtersOnRelations
- findExactlyOneOrFailHandler
- findOneOrFailHandler
- flushMode
- forceEntityConstructor
- forceUndefined
- forceUtcTimezone
- highlighter
- host
- hydrator
- ignoreDeprecations
- ignoreUndefinedInQuery
- implicitTransactions
- loadStrategy
- logger
- loggerFactory
- metadataCache
- metadataProvider
- migrations
- multipleStatements
- name
- namingStrategy
- onCreateConnection
- onQuery
- password
- persistOnCreate
- pool
- populateAfterFlush
- populateWhere
- port
- preferReadReplicas
- preferTs
- processOnCreateHooksEarly
- propagationOnPrototype
- replicas
- resultCache
- schema
- schemaGenerator
- seeder
- serialization
- subscribers
- timezone
- upsertManaged
- useBatchInserts
- useBatchUpdates
- user
- validateRequired
- verbose
Properties
optionalallowGlobalContext
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
Default options for entity assignment via em.assign().
optionalautoJoinOneToOneOwner
Automatically join the owning side of 1:1 relations when querying the inverse side.
optionalautoJoinRefsForFilters
Automatically join M:1 and 1:1 relations when filters are defined on them. Important for implementing soft deletes via filters.
optionalbaseDir
Base directory for resolving relative paths.
optionalbatchSize
Number of entities to process in each batch for batch inserts/updates.
optionalinheritedcharset
Character set for the connection.
optionalinheritedclientUrl
Full client connection URL. Overrides individual connection options.
optionalinheritedcollate
Collation for the connection.
optionalcolors
Enable colored output in logs.
optionalcontext
Callback to get the current request context's EntityManager. Used for automatic context propagation in web frameworks.
Type declaration
Parameters
name: string
Returns undefined | EntityManager<IDatabaseDriver<Connection>>
optionalcontextName
Name of the context for multi-ORM setups.
optionaldataloader
Enable dataloader for batching reference loading.
trueorDataloaderType.ALL: Enable for all relation typesfalseorDataloaderType.NONE: Disable dataloaderDataloaderType.REFERENCE: Enable only for scalar referencesDataloaderType.COLLECTION: Enable only for collections
optionalinheriteddbName
Name of the database to connect to.
optionaldebug
Enable debug logging.
Can be true for all namespaces or an array of specific namespaces.
Available namespaces: 'query', 'query-params', 'discovery', 'info'.
optionaldisableIdentityMap
Disable the identity map. When disabled, each query returns new entity instances. Not recommended for most use cases.
optionaldisableTransactions
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
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.
Type declaration
Parameters
Returns Driver
optionalinheriteddriverOptions
Additional driver-specific options. The object will be deeply merged with internal driver options.
optionaldynamicImportProvider
Custom dynamic import provider for loading modules.
Type declaration
Parameters
id: string
Returns Promise<unknown>
optionalembeddables
Embeddable entity configuration options.
Type declaration
prefixMode: EmbeddedPrefixMode
Mode for generating column prefixes for embedded properties.
optionalensureDatabase
Ensure the database exists when initializing the ORM.
When true, will create the database if it doesn't exist.
optionalensureIndexes
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
Array of entity classes or paths to entity modules. Paths support glob patterns for automatic discovery.
optionalentitiesTs
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.
optionalentityGenerator
Entity generator (code generation) configuration options.
optionalentityManager
Custom entity manager class to use.
optionalentityRepository
Custom base repository class for all entities. Entity-specific repositories can still be defined and will take precedence.
optionalextensions
ORM extensions to register (e.g., Migrator, EntityGenerator, SeedManager).
Extensions registered here are available via shortcuts like orm.migrator.
optionalfilters
Global entity filters to apply. Filters are applied by default unless explicitly disabled.
optionalfiltersOnRelations
Apply filters to relations in queries.
optionalfindExactlyOneOrFailHandler
Custom error handler for em.findExactlyOneOrFail() when entity count is not exactly one.
Used when strict mode is enabled.
Type declaration
Parameters
entityName: string
Name of the entity being queried
where: Dictionary | IPrimaryKeyValue
Query conditions
Returns Error
Error instance to throw
optionalfindOneOrFailHandler
Custom error handler for em.findOneOrFail() when no entity is found.
Type declaration
Parameters
entityName: string
Name of the entity being queried
where: Dictionary | IPrimaryKeyValue
Query conditions
Returns Error
Error instance to throw
optionalflushMode
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
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
Convert null values from database to undefined when hydrating entities.
optionalforceUtcTimezone
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
Syntax highlighter for SQL queries in logs.
optionalinheritedhost
Database server hostname.
optionalhydrator
Custom hydrator class for assigning database values to entities.
optionalignoreDeprecations
Ignore deprecation warnings.
Can be true to ignore all or an array of specific deprecation labels.
optionalignoreUndefinedInQuery
Ignore undefined values in find queries instead of treating them as null.
optionalimplicitTransactions
Enable implicit transactions for all write operations. When enabled, all queries will be wrapped in a transaction. Disabled for MongoDB driver by default.
optionalloadStrategy
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
Custom logger function for ORM output.
Type declaration
Parameters
message: string
Returns void
optionalloggerFactory
Factory function to create a custom logger instance.
Type declaration
Parameters
options: LoggerOptions
Returns Logger
optionalmetadataCache
Metadata cache configuration for improved startup performance.
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.Parameters
rest...params: any[]
Returns SyncCacheAdapter
optionalcombined?: string | boolean
Combine all metadata into a single cache file. Can be
truefor 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
Metadata provider class for entity discovery.
Built-in options: ReflectMetadataProvider (default), TsMorphMetadataProvider.
Type declaration
Parameters
Returns MetadataProvider
optionaluseCache?: () => boolean
Returns boolean
optionalmigrations
Migration configuration options.
optionalinheritedmultipleStatements
Enable multiple statements in a single query. Required for importing database dump files. Should be disabled in production for security.
optionalinheritedname
Name of the connection (used for logging when replicas are used).
optionalnamingStrategy
Custom naming strategy class for mapping entity/property names to database table/column names.
Built-in options: UnderscoreNamingStrategy, MongoNamingStrategy, EntityCaseNamingStrategy.
Type declaration
Returns NamingStrategy
optionalinheritedonCreateConnection
Callback to execute when a new connection is created.
Type declaration
Parameters
connection: unknown
Returns Promise<void>
optionalonQuery
Hook to modify SQL queries before execution. Useful for adding observability hints or query modifications.
Type declaration
Parameters
sql: string
The generated SQL query
params: readonly unknown[]
Query parameters
Returns string
Modified SQL query
optionalinheritedpassword
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.
optionalpersistOnCreate
Automatically call em.persist() on entities created via em.create().
optionalinheritedpool
Connection pool configuration.
optionalpopulateAfterFlush
Mark all relations as populated after flush for new entities. This aligns serialized output of loaded entities and just-inserted ones.
optionalpopulateWhere
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
Database server port number.
optionalpreferReadReplicas
Prefer read replicas for read operations when available.
optionalpreferTs
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
Property onCreate hooks are normally executed during flush operation.
With this option, they will be processed early inside em.create() method.
optionalpropagationOnPrototype
Enable propagation of changes on entity prototypes.
optionalreplicas
Read replica connection configurations. Each replica can override parts of the main connection options.
optionalresultCache
Result cache configuration for query result caching.
Type declaration
optionaladapter?: new (...params) => CacheAdapter
Cache adapter class to use.
Parameters
rest...params: any[]
Returns CacheAdapter
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
Default database schema to use.
optionalschemaGenerator
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 configuration options.
optionalserialization
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
Event subscribers to register. Can be class references or instances.
optionaltimezone
Timezone to use for date operations.
optionalupsertManaged
When upsert creates a new entity, mark it as managed in the identity map.
optionaluseBatchInserts
Use batch insert queries for better performance.
optionaluseBatchUpdates
Use batch update queries for better performance.
optionalinheriteduser
Database user name.
optionalvalidateRequired
Validate that required properties are set on new entities before insert.
optionalverbose
Enable verbose logging of internal operations.
MikroORM configuration options.
https://mikro-orm.io/docs/configuration