我正在使用NestJS Documentation中的示例来说明如何设置Sequelize数据库连接。如何使用Sequelize和TypeScript for NestJS设置与两个以上数据库的连接。
答案 0 :(得分:2)
您可以在databaseProviders
中设置多个Sequelize连接:
export const databaseProviders = [
{
provide: 'SequelizeCatToken',
useFactory: async () => {
const sequelize = new Sequelize({
dialect: 'mysql',
host: 'localhost',
port: 3306,
username: 'catroot',
password: 'catpassword',
database: 'cats',
});
sequelize.addModels([Cat]);
await sequelize.sync();
return sequelize;
},
},
{
provide: 'SequelizeDogToken',
useFactory: async () => {
const sequelize = new Sequelize({
dialect: 'mysql',
host: 'localhost',
port: 3306,
username: 'doogroot',
password: 'dogpassword',
database: 'dogs',
});
sequelize.addModels([Dog]);
await sequelize.sync();
return sequelize;
},
},
];
答案 1 :(得分:0)
您必须使用 name
进行连接,这是强制性的。
const defaultOptions = {
dialect: 'postgres',
port: 5432,
username: 'user',
password: 'password',
database: 'db',
synchronize: true,
};
@Module({
imports: [
SequelizeModule.forRoot({
...defaultOptions,
host: 'user_db_host',
models: [User],
}),
SequelizeModule.forRoot({
...defaultOptions,
name: 'albumsConnection',
host: 'album_db_host',
models: [Album],
}),
],
})
export class AppModule {}
这是 Nest
中的文档