TypeORM:如何连接多个数据库
在 TypeORM 中,您只需创建多个数据源即可简单地同时连接到多个数据库。
步骤
- 设置您的数据源:
xport const dataSourceOne = new DataSource({
database: 'kindacode_example',
entities: [User, Post, Comment],
type: 'postgres',
port: 5432,
host: 'localhost',
username: 'snowball',
password: '123456',
synchronize: true,
});
export const dataSourceTwo = new DataSource({
database: 'other_db',
entities: [Product, Order],
type: 'postgres',
port: 5432,
host: 'localhost',
username: 'badman',
password: 'supersecret',
synchronize: true,
});
2.下一步是初始化连接(通常放在你项目的入口文件,如app.js、index.js、server.js等):
import { dataSourceOne } from '...';
import { dataSourceTwo } from '...';
/* Put these lines in an async function */
await dataSourceOne.initialize();
await dataSourceTwo.initialize();
3.您可以通过以下方式与数据库进行通信:
import { dataSourceOne } from '...';
import { dataSourceTwo } from '...';
/* Place these code lines in an async function */
const userRepository = dataSourceOne.getRepository(User);
const users = await userRepository.find();
console.log(users);
const productRepsoitory = dataSourceTwo.getRepository(Product);
const products = await productRepsoitory.find();
console.log(products);
请注意,连接的数据库类型可以不同(PostgreSQL、MySQL、MongoDB 等)。如果遇到错误,请尝试将typeorm更新到最新版本。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。