本文介绍了使用sequelize根据express.js中的路由更改数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据路由在 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中的路由更改数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 19:33