To dynamically change the database connection in NestJS Sequelize, you can follow these steps: 1. Inject the Sequelize instance from the sequelize module in your service or controller
import { Sequelize } from 'sequelize-typescript';
import { Inject } from '@nestjs/common';
@Injectable()
export class MyService {
constructor(@Inject(Sequelize) private readonly sequelize: Sequelize) {}
}
setDbConnection(config: any): void {
this.sequelize.close(); // close the previous connection
this.sequelize.config.database = config.database;
this.sequelize.config.username = config.username;
this.sequelize.config.password = config.password;
this.sequelize.config.host = config.host;
this.sequelize.config.port = config.port;
this.sequelize.config.dialect = config.dialect;
this.sequelize.config.logging = config.logging;
this.sequelize.authenticate();
}
const newDbConfig = {
database: 'new-db',
username: 'admin',
password: 'admin',
host: 'localhost',
port: 3306,
dialect: 'mysql',
logging: false
};
this.setDbConnection(newDbConfig);
Note that this example assumes you are using sequelize-typescript and have already configured your Sequelize instance with the database connection information.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-17 07:43:36 +0000
Seen: 14 times
Last updated: Jun 17 '23
What is the process for implementing a Many to Many relationship using NestJs Sequlize and Mysql2?
How to deal with an operational error when connecting Django to MySQL?
In this scenario, what is the reason for the WHERE clause in MySQL to produce zero rows?
How can multiple queries be merged into a single stored procedure in MySQL?
What is the method for verifying the existence of a mysql database?
What does "waiting for handler commit" mean in relation to the slow writes experienced in MySQL 8?
How can Spring Boot and Mysql be utilized for CRUD operations?
How can I refine the results for a specific column in MySQL?