Actually, I am raising this question after trying all possibilities and previous questions answers. but, I don't find any clue that's why i am asking
Statement :
Here i am working based on Multi-Tenant Architecture. so every client organisations need to have their own Databases and they are relational. so, in my case i need to work with " 'n' no of databases ".to solve my case i need to establish the database connection dynamically based on the every user request to their individual DB and need to perform CRUD operations (Note : concurrent operations need to perform on their own db without disturb others).
My preference :
So, initially i done some research and planned to work with Node + PostgreSQL + Sequelize
Problem :
Then i started to research how to establish connection dynamically in sequelize during every api request but i found nothing. because in all tutorial and stackoverflow questions and answers the DB connections are not fully dynamic and the sequelize connection is established during the app initialisation and models are bounded with sequelize db connection (please correct me if my understanding is wrong).
Solution :
I searched about other alternatives for sequelize. then, i found in postgresql native pg driver's dynamic db connection it's like
const pool = new Pool({
user: 'postgres',
host: '127.0.0.1',
database: 'todos-dev',
password: 'aaaaa',
port: 5432,
})
let query = 'SELECT * FROM "Todos"';
pool.query(query, (error, results) => {
if (error) {
throw error
}
pool.end();
res.status(200).json(results.rows)
})
then i found the queries are Raw SQL and not ORM.
Questions :
I also have the same problem. Multiple databases are in the same MYSQL, and each database has the same model definition. I have checked the sequelize source code and realized that one sequelize instance can solve the problem of multiple DB connections.
Connection configuration:
{
"username": "root",
"password": "123456",
"database": "",
"port": 3306,
"dialect": "MySQL"
}
How to get model:
static getModel(modelType, dbname) {
let model = sequelize.models[module.name];
model.tableName = {
schema: dbname,
tableName: modelType
};
sequelize.dialect.supports.schemas = true;
return model;
}
This allows you to dynamically query across multiple databases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With