node.js - Typeorm连接到多个数据库

标签 node.js postgresql typescript typeorm koa2

我在后端项目中使用 node.js 、TS 和 typeorm。

我需要根据我发送的参数连接到中间件中的不同数据库。 而且我必须将查询发送到数据库。

管理配置

[
  {
    "name": "default",
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "postgres",
    "password": "12345",
    "database": "dbOne"
  },
  {
    "name": "second-connection",
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "postgres",
    "password": "12345",
    "database": "dbTwo"
  }
]

这是我的连接设置。 在我这样做之后,我尝试连接到中间件。

   const connectionOptions = await getConnectionOptions("second-connection");
   const conTwo = await createConnection(connectionOptions);

   const managerTwo = getManager("second-connection");

   const resultTwo = await managerTwo
      .createQueryBuilder(SysCompany, "company")
      .getOne();

   console.log(resultTwo);

我想我可以连接到数据库,但我在使用存储库时遇到了问题。

错误

EntityMetadataNotFound:未找到“SysCompany”的元数据。

@Entity()
export class SysCompany extends CoreEntityWithTimestamp {

  @Column({ length: 100 })
  name: string;

  // FK
  // SysPersonnel
  @OneToMany(type => SysPersonnel, personnel => personnel.sysCompany)
  sysPersonnels: SysPersonnel[];

}

最佳答案

也许 typeORM 找不到您的 JavaScript 实体。我前段时间遇到过这个问题。您可以执行以下操作:

  • 在构建项目后检查目标文件夹。您的 SysCompany.js 可用吗?
  • 在配置中设置 entities 属性。它必须包含您的 JS 实体的路径。 typeORM 文档声明“每个实体都必须在您的连接选项中注册”。
{
 "name": "second-connection",
 "type": "postgres",
 "host": "localhost",
 "port": 5432,
 "username": "postgres",
 "password": "12345",
 "database": "dbTwo"
 "entities": ["<path to entities>/**/*.js"]
}

我还建议使用 JavaScript 配置文件。您的 ormconfig.js 然后可以使用 __dirname (当前模块的目录名称)来设置路径。因此,如果您的目录如下所示:

project/ormconfig.js
project/dist/entity/SysCompany.js
project/dist/entity/OtherEntity.js

您可以使用这样的配置:

import {join} from "path";
...
  entities: [
    join(__dirname, "dist/entity/**/*.js")
  ],
...

您还可以通过使用基本配置对象来防止重复。

import {join} from "path";

const baseOptions = {
  type: "postgres",
  host: "localhost",
  port: 5432,
  username: "postgres",
  password: "12345",
  entities: [
    join(__dirname, "dist/entity/**/*.js")
  ]
}

const defaultConfig = Object.assign({
  name: "default",
  database: "dbOne",
}, baseOptions);

const secondConfig = Object.assign({
  name: "second-connection",
  database: "dbTwo",
}, baseOptions);

module.exports = [ defaultConfig, secondConfig ];

在您打开连接的文件中,您可以使用导入:

import { secondConfig } from "<path to file>/ormconfig";

const conTwo = await createConnection(secondConfig);

关于node.js - Typeorm连接到多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54721210/

相关文章:

javascript - 无法从子进程获取输出

node.js - 为什么ZeroMQ消息会被扰乱?

java - JDBC Postgres 驱动程序是否有办法设置 "client_encoding"以连接到数据库?

node.js - 回滚到旧版本的 firebase 函数(谷歌云函数)

node.js - 使用对象更新准备好的语句

ruby-on-rails - before_save 期间的方法错误

typescript - 限制函数参数的可能值

javascript - 无法在基于 jest 和 vue-test-utils 的测试项目中使用 vue.js 的 ES6 模块

javascript - Visual Studio 无法识别导入的 npm 包?

node.js - Mongoose 价格类型