【问题标题】:Proper way to create connection to db in Typeorm - Nodejs在 Typeorm 中创建与 db 的连接的正确方法 - Nodejs
【发布时间】:2022-06-23 05:50:31
【问题描述】:

我是 typeorm 的新手,正在尝试创建与 db 的连接。我阅读了 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));

我有点困惑。我应该使用什么方法在上述两者之间创建与 db 的连接?

【问题讨论】:

  • 我也面临同样的困惑。你有这方面的参考吗?

标签: node.js database typeorm


【解决方案1】:

对于遇到此问题的下一个人,createConnection 已被弃用,转而使用 new DataSource。见这里:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多