NodeJS 如何在NestJS中使用多个sequelize DB连接

axr492tv  于 2023-04-05  发布在  Node.js
关注(0)|答案(2)|浏览(209)

我正在使用NestJS Documentation中的示例来设置Sequelize DB连接。如何使用Sequelize和TypeScript为NestJS设置到两个以上数据库的连接。

7bsow1i6

7bsow1i61#

您可以在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;
    },
  },
];
2vuwiymt

2vuwiymt2#

您必须使用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中的文档

相关问题