javascript - 使用 sequelize 根据 express.js 中的路由更改数据库连接

标签 javascript node.js express sequelize.js

是否可以根据路由更改 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/

相关文章:

javascript - onkeypress 事件在 Opera Mini 中不起作用

javascript - console.dir 和 console.log 有什么区别?

javascript - 如何使用 jquery 查找并选择所有具有数据属性并以特定单词开头的元素?

node.js - 如何在node js中使用express重定向后app.get

node.js - Webstorm Nodejs 约定空间

javascript - 有没有办法返回当前不在聚类组内的所有标记的列表?

node.js - 如何在 Typeorm 中查询数组

mysql - 是否没有选项可以在 sequelize 模型中映射列名

mysql - 为什么我从 docker Node 应用程序连接到 localhost MySQL 时出现 ECONNREFUSED?

mysql - 如何正确设置 Node js Rest api