Node.js 中多个 Mysql 数据库的池连接

Tha*_*eez 5 mysql multi-tenant node.js

I am trying to create a multi tenant node.js application (with also sub domains) where each user has their own database under a single host, (say an rds instance).

So it will be easier for me to handover the database to that particular user to access that particular database.

So my problem here is when an user request the api, is it possible to dynamically change the database name based on the request.

One thing that popped up in my mind is to create a pool connection with credentials that have access to all database and add the database name in the query, in this way i can achieve what i want, but just out of curiosity is it possible to add the database name after the connection pool has been created, without adding it to the query.

My solution :

select * from 'dbname'.users
Run Code Online (Sandbox Code Playgroud)

What i am looking for:

const pool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    // database: process.env.DB_NAME, leaving out since db name should be dynamic
    connectionLimit: 5,
    supportBigNumbers: true,
});
Run Code Online (Sandbox Code Playgroud)

And in middleware when i need db access, i should be able to set the db name based on the request.

The reason behind this is, I have created the application and wrote the queries without the database name, now i should add the logic to every query in my application.

ido*_*mun 3

阅读官方文档: https://github.com/mysqljs/mysql/blob/master/Readme.md#connection-options

提到数据库选项是可选的。您可以在初始化池时放弃此选项,并在 SQL 查询中指定正确的数据库。您无法在没有数据库配置的情况下创建池,然后将数据库设置为连接。您必须为此目的使用查询。