在express.js中使用sequelize更改数据库连接,具体取决于路由
是否有可能改变数据库连接在sequelize
取决于路线?
例如,用户可以访问2个不同的安装在一个网站: – example.com/foo
– example.com/bar
login后,用户被redirect到example.com/foo
为了获得foo
站点的所有任务,他们需要访问example.com/foo/tasks
bar
网站使用一个单独的数据库,因此,如果他们想获得他们所有的任务bar
他们必须去example.com/bar/tasks
每个安装都有自己的数据库,所有的数据库都有相同的模式。
是否可以根据访问哪个路由来更改数据库连接?
*login只发生一次
这个有可能。 有很多方法可以做到这一点。 以下是我可能会接近的方式。
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. }
也就是说,当你想在两者之间复制模式时,你将不得不面对一些有趣的问题,但是这对于另一个问题可能是最好的。
我希望这有帮助!
我认为根据路线更改collections更好。 在同一个数据库中有foo_tasks
集合和bar_tasks
集合。
或者在tasks
集合中具有指定任务是“foo任务”还是“小节任务”的属性type
。