我是 typeorm 的新手,正在尝试创建与数据库的连接。我阅读了 typeorm 的文档并找到了这段代码,它使用 DataSource 创建连接:
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))
但是当在其他来源中搜索一些参考资料时,他们使用 createConnection 来代替:
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));
我有点困惑。我应该使用什么方法在上述两者之间创建与数据库的连接?
对于遇到此问题的下一个人,
createConnection
已被弃用,转而使用 new DataSource
。请看这里:
https://typeorm.io/changelog#030httpsgithubcomtypeormtypeormpull8616-2022-03-17