简体   繁体   中英

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. How can I setup connections to more than two databases using Sequelize and TypeScript for NestJS.

You can just setup multiple Sequelize connections in your databaseProviders :

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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