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:

  1. import {createConnection} from "typeorm";
  2. createConnection({
  3. type: "mysql",
  4. host: "localhost",
  5. port: 3306,
  6. username: "root",
  7. password: "admin",
  8. database: "test",
  9. entities: [
  10. __dirname + "/entity/*.js"
  11. ],
  12. synchronize: true,
  13. }).then(connection => {
  14. // here you can start to work with your entities
  15. }).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.