问题描述
sequelize中是否可以根据路由改变数据库连接?
Is it possible to change the database connection in sequelize depending on the route?
例如,用户可以访问网站中的 2 个不同的安装:- example.com/foo- example.com/bar
For example, Users have access to 2 different installations in a website:
- example.com/foo
- example.com/bar
登录后,用户会被重定向到 example.com/foo要获取 foo 站点的所有任务,他们需要访问 example.com/foo/tasks
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
bar 站点使用单独的数据库,因此如果他们想获得 bar 的所有任务,他们必须访问 example.com/bar/任务
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?
*只登录一次
推荐答案
这是可能的.有很多方法可以做到这一点.以下是我可能会采用的方法.
This is possible. There are a number of ways to do this. Here's how I might approach it.
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.
我希望这会有所帮助!
这篇关于使用 sequelize 根据 express.js 中的路由更改数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)