NestJS+TypeORM运行时切换SQLite数据库遇实体元数据错误
Key Issues & Solutions
Explicitly Register Entities for Dynamic Connections
Dynamic connections don’t inherit entity configurations from your default connection. When creating a new SQLite connection, you must list all entities explicitly, just like in yourapp.module.tssetup. This ensures TypeORM loads the metadata for your entities in the new connection context.Example
getDbConnectionimplementation:import { getConnectionManager, Connection, ConnectionOptions } from 'typeorm'; import { Player } from './entities/player.entity'; // Import all other entities used in your app async function getDbConnection(dbIdentifier: string): Promise<Connection> { const connectionManager = getConnectionManager(); const connectionName = `sqlite_${dbIdentifier}`; if (connectionManager.has(connectionName)) { return connectionManager.get(connectionName); } const connectionOptions: ConnectionOptions = { name: connectionName, type: 'sqlite', database: `./databases/${dbIdentifier}.sqlite`, entities: [Player, /* Add all your entities here */], synchronize: true, // Match your default connection's sync setting }; const connection = connectionManager.create(connectionOptions); await connection.connect(); // Wait for connection to fully initialize return connection; }Use the Dynamic Connection’s EntityManager/Repository
In yourplayer.service.ts, ensure you’re pulling the repository or EntityManager directly from the dynamic connection you created—not the default connection. Mixing connections will lead to missing metadata errors.Example service logic:
async getPlayer(userId: string, user: User) { const dbConnection = await getDbConnection(user.dbIdentifier); const playerRepo = dbConnection.getRepository(Player); return playerRepo.findOne({ where: { userId } }); }Verify Entity Path Resolution
If using glob patterns for entities (e.g.,dist/**/*.entity{.ts,.js}), use absolute paths to avoid context-dependent resolution issues. Leverage__dirnameto ensure consistency:entities: [__dirname + '/../**/*.entity{.ts,.js}'],Confirm Connection Initialization
Always await theconnect()method when creating a new connection. Skipping this can lead to attempting to use the connection before its entity metadata is loaded. You can debug by loggingconnection.entityMetadatasto check if your entities are registered.
内容的提问来源于stack exchange,提问作者sirzento

