问题
Is it possible to change the database connection in sequelize depending on the route?
For example, Users have access to 2 different installations in a website:
- example.com/foo
- example.com/bar
Upon login users are redirected to example.com/foo
To get all their tasks for the foo site, they need to visit example.com/foo/tasks
The bar site uses a separate database and thus if they want to get all their tasks for bar they have to go to example.com/bar/tasks
Every installation has its own database, and all databases have the same schema.
Is it possible to change the database connection depending on which route is visited?
*login only occurs once
回答1:
This is possible. There are a number of ways to do this. Here's how I might approach it.
Router.js
var router = express.Router()
// This assumes the database is always the 2nd param,
// otherwise you have to enumerate
router.use('/:database/*', function(req, res, next){
req.db = req.params.database;
next();
}
Connection.js
var fooDB = new Sequelize('postgres://user:pass@example.com:5432/foo');
var barDB = new Sequelize('postgres://user:pass@example.com:5432/bar');
module.exports = {
foo: fooDB,
bar: barDB,
}
Tasks.js
var connection = require('connection);
function getTasks(req, params){
var database = connection[req.db];
//database now contains the db you wish to access based on the route.
}
That said, there are some interesting problems you'll have to face when you want to duplicate the schema across both, but that's probably best for another question.
I hope this helps!
回答2:
I think is better to change collections depending on the route.
Have foo_tasks collection and bar_tasks collection in the same database.
Or have the attribute type in the tasks collection that specifies if the task is a "foo task" or a "bar task".
来源:https://stackoverflow.com/questions/30202056/change-database-connection-depending-on-route-in-express-js-with-sequelize