Creating a connection to the database

Now, when our entity is created, let’s create an index.ts (or app.ts whatever you call it) file and set up our connection there:

  1. import "reflect-metadata";
  2. import {createConnection} from "typeorm";
  3. import {Photo} from "./entity/Photo";
  4. createConnection({
  5. type: "mysql",
  6. host: "localhost",
  7. port: 3306,
  8. username: "root",
  9. password: "admin",
  10. database: "test",
  11. entities: [
  12. Photo
  13. ],
  14. synchronize: true,
  15. logging: false
  16. }).then(connection => {
  17. // here you can start to work with your entities
  18. }).catch(error => console.log(error));

We are using MySQL in this example, but you can use any other supported database.To use another database, simply change the type in the options to the database type you are using:mysql, mariadb, postgres, cockroachdb, sqlite, mssql, oracle, cordova, nativescript, react-native,expo, or mongodb.Also make sure to use your own host, port, username, password and database settings.

We added our Photo entity to the list of entities for this connection.Each entity you are using in your connection must be listed there.

Setting synchronize makes sure your entities will be synced with the database, every time you run the application.