Loading all entities from the directory
Later, when we create more entities we need to add them to the entities in our configuration.This is not very convenient, so instead we can set up the whole directory, from where all entities will be connected and used in our connection:
import {createConnection} from "typeorm";
createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "admin",
database: "test",
entities: [
__dirname + "/entity/*.js"
],
synchronize: true,
}).then(connection => {
// here you can start to work with your entities
}).catch(error => console.log(error));
But be careful with this approach.If you are using ts-node
then you need to specify paths to .ts
files instead.If you are using outDir
then you’ll need to specify paths to .js
files inside outDir directory.If you are using outDir
and when you remove or rename your entities make sure to clear outDir
directoryand re-compile your project again, because when you remove your source .ts
files their compiled .js
versionsaren’t removed from output directory and still are loaded by TypeORM because they are present in the outDir
directory.