node.jsdatabaseconnectiontypeorm

Proper way to create connection to db in Typeorm - Nodejs


I'm newbie to typeorm and trying to create a connection to db. I read the typeorm's doc and found this code, it uses DataSource to create connection:

import "reflect-metadata"
import { DataSource } from "typeorm"
import { Photo } from "./entity/Photo"

const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "root",
    password: "admin",
    database: "test",
    entities: [Photo],
    synchronize: true,
    logging: false,
})

AppDataSource.initialize()
    .then(() => {
        // here you can start to work with your database
    })
    .catch((error) => console.log(error))

But when searching for some references in other sources, they use createConnection instead:

import { createConnection } from "typeorm"

createConnection({
  type: "mysql",
  host: "localhost",
  port: 3306,
  username: "root",
  password: "mysql",
  database: "mysql",
  entities: [
     __dirname + "/entity/*.ts"
  ],
  synchronize: true,
  logging: false
}).then(async connection => {
…
…
}).catch(error => console.log(error));

I'm a bit confused. What approach should I use for creating connection to db between those two above?


Solution

  • For the next person that comes across this issue, createConnection has been deprecated in favor of using new DataSource. See here:

    https://typeorm.io/changelog#030httpsgithubcomtypeormtypeormpull8616-2022-03-17