admin管理员组

文章数量:1394046

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/foo - example/bar

Upon login users are redirected to example/foo To get all their tasks for the foo site, they need to visit example/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/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

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./foo - example./bar

Upon login users are redirected to example./foo To get all their tasks for the foo site, they need to visit example./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./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

Share Improve this question edited May 14, 2015 at 2:36 VulgarBinary 3,5994 gold badges22 silver badges55 bronze badges asked May 12, 2015 at 21:50 zesk8zesk8 1811 gold badge2 silver badges7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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:[email protected]:5432/foo');
var barDB = new Sequelize('postgres://user:[email protected]: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!

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".

本文标签: javascriptChange database connection depending on route in expressjs with sequelizeStack Overflow