是否可以根据路由更改 sequelize
中的数据库连接?
例如,用户可以访问网站中的 2 个不同安装:
- example.com/foo
- example.com/bar
登录后,用户将被重定向到 example.com/foo
要获得 foo
站点的所有任务,他们需要访问 example.com/foo/tasks
bar
站点使用一个单独的数据库,因此如果他们想要获取 bar
的所有任务,他们必须转到 example.com/bar/任务
每个安装都有自己的数据库,所有数据库都有相同的模式。
是否可以根据访问的路由更改数据库连接?
*登录只发生一次
最佳答案
这是可能的。有多种方法可以做到这一点。以下是我可能采用的方法。
路由器.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();
}
连接.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,
}
任务.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.
}
也就是说,当您想在两者之间复制模式时,您将不得不面对一些有趣的问题,但这可能是另一个问题的最佳选择。
希望对您有所帮助!
关于javascript - 使用 sequelize 根据 express.js 中的路由更改数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202056/