Typeorm:在一个连接中使用多个数据库Postgresql - nodejs



我遵循这个文档,它是不可能在一个连接中与2个数据库通信的:

https://typeorm.io//多个连接/using-multiple-databases-in-a-single-connection

我成功地连接了2个不同的连接,但我需要在一个连接中完成。在这一章的末尾,它是这样写的:

此特性仅支持mysql和mssql数据库

我正在使用Postgresql。这是问题吗?

如果有人有一个解释,一个完整的例子或一个存储库,这将是了不起的

如果它能帮助任何人,这就是解决方案。

CREATE EXTENSION postgres_fdw;
CREATE SERVER <connection_name>
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host <host>, dbname <dbname>, port <port>);
CREATE USER MAPPING FOR <user>
SERVER <connection_name>
OPTIONS (user <user>, password <password>);
IMPORT FOREIGN SCHEMA <schema_name>
LIMIT TO (<table_name>)
FROM SERVER <connection_name> INTO <schema_name>;

来源:https://www.akinjide.me/2017/cross-database-querying-in-postgresql/

TypeOrmModule通过添加多个具有不同连接名称的模块来提供多个数据库连接处理。

注意:name属性很重要

@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
name: 'Connection1', // this is what will be used
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'database1',
}),
TypeOrmModule.forRoot({
type: 'postgres',
name: 'Connection2',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'database2',
}),
],
controllers: [AppController],
providers: [
],
})
export class AppModule {}
现在在你的UserModule 中

// same entity can be used on different connections or if you want you can use different
@Module({
imports: [
TypeOrmModule.forFeature([UserEntity], 'Connection1'),
TypeOrmModule.forFeature([UserEntity], 'Connection2'),
],
providers: [UserService]
})

用户服务

@Injectable()
class UserService {
constructor (
@InjectRepository(UserEntity, 'Connection1') private userCon1Repo: Repository<UserEntity>,
@InjectRepository(UserEntity, 'Connection2') private userCon2Repo: Repository<UserEntity>,
}

主要的要点是,如果你想维护多个连接,你必须在forRoot或forRootAsyn中配置连接时命名连接,当注入实体时,你需要在第二个参数中提供连接名称。

我认为没有提供的名称是default.

Sequelize也是一样。

最新更新