I'm building a multi tenant application, using Nodejs, Seuqelize and Mysql.
I've decided on an approach where each tenant gets a separate logical database(From what i understand, in Postgres this would be called a "schema", but in Mysql it's simply a "database"). I chose this approach, because in my case, databases would need to be created after the Node process already started, and a DB connection was made, and there is no way to configure them in advance.
I do not know how to dynamically(during an HTTP request) tell a Sequelize model, which database should be used, for the particular query.
For example, let's say i have this GET/photo/ route:
router.get('photo/', async function (req, res) {
const tenantId = req.user.id//Assume the auth middleware provides a tenant id.
try {
const records = await Photo.findAll()//Need to tell the Photo model, which database/schema this
//should be queried in
res.json(records);
} catch (error) {
console.log(error)
res.sendStatus(500)
}
})
Of course, if i were using raw queries, i would just say
SELECT * FROM ${tenantId}.photo
But if i'm using Sequelize, i want to actually enjoy its full features.
How can i tell the Photo model, which database to use? Let me clarify again, that i'm not talking about a physical database, but just a logical one. The host is the same host, and i have only one connection. The initial "database" argument to the Sequelize config is a database that holds all tenants, with references to their respective databases.
question from:
https://stackoverflow.com/questions/65852197/how-to-dynamically-select-the-databaseor-schema-in-a-sequelize-model 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…