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:
import "reflect-metadata";
import {createConnection} from "typeorm";
import {Photo} from "./entity/Photo";
createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "admin",
database: "test",
entities: [
Photo
],
synchronize: true,
logging: false
}).then(connection => {
// here you can start to work with your entities
}).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.