简体   繁体   English

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

[英]How to work with more than one sequelize DB connection in NestJS

I am using the example from the NestJS Documentation on how to setup the Sequelize DB connection.我正在使用 NestJS文档中关于如何设置 Sequelize DB 连接的示例。 How can I setup connections to more than two databases using Sequelize and TypeScript for NestJS.如何使用 Sequelize 和 TypeScript for NestJS 建立与两个以上数据库的连接。

You can just setup multiple Sequelize connections in your databaseProviders : 您可以在您的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;
    },
  },
];

You must use name for the connection, its mandatory.您必须为连接使用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 {}

Here is the documentation in Nest这是Nest 中的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM