我将node.js,TS和typeorm用于后端项目。
我需要根据我发送的参数连接到中间件中的其他数据库。 而且我必须将查询发送到数据库。
ormconfig
[
{
"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[];
}
答案 0 :(得分:0)
也许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);