node.js - Sequelize : connect to database on run time based on the request

标签 node.js postgresql orm sequelize.js sequelize-cli

我正在开发一个 node.js 应用程序,我需要连接到多个数据库。其中一个数据库是中央数据库,其中包含所有人共有的信息。然后是国家级数据库,其中根据国家/地区存储数据。

我正在应用中使用 sequelize ORM。
数据库是postgresql。
框架是明确的。

问题是我想根据请求决定运行时使用哪个数据库,模型应该自动连接到适当的数据库。我看过this问题,但没有发现它有帮助。

我也查看了其他论坛,但没有找到任何东西。

最佳答案

你需要创建对应于你的每个数据库的对象,并且在每个这个对象上你需要实例化Sequelize。此外,对于每个 sequelize 实例,您需要导入模型(假设所有这些数据库都具有完全相同的表和模型表示)。

import Sequelize from 'sequelize';

let connectionsArray = [
    'postgres://user:pass@example.com:5432/country1',
    'postgres://user:pass@example.com:5432/country2',
    'postgres://user:pass@example.com:5432/country3',
];

let country1DB, country2DB, country3DB;
country1DB = country2DB = country3DB = {};
country1DB.Sequelize = country2DB.Sequelize = country3DB.Sequelize = Sequelize;

country1DB.sequelize = new Sequelize(connectionsArray[0]);
country2DB.sequelize = new Sequelize(connectionsArray[1]);
country3DB.sequelize = new Sequelize(connectionsArray[2]);

// here you need to access the models path, maybe with fs module
// iterate over every model and import it into every country sequelize instance
// let's assume that models' paths are in simple array
models.forEach(modelFile => {
    let model1DB = country1DB.sequelize.import(modelFile);
    let model2DB = country2DB.sequelize.import(modelFile);
    let model3DB = country3DB.sequelize.import(modelFile);

    country1DB[model1DB.name] = model1DB;
    country2DB[model2DB.name] = model2DB;
    country3DB[model3DB.name] = model3DB;
});

// now every country?DB object has it's own sequelize instance and all model definitions inside
export {
    country1DB,
    country2DB,
    country3DB
};

这只是一些示例代码,需要重构才能发挥作用(引入一些循环等)。它应该只是向您展示如何在单个应用程序中使用多个数据库的想法。如果您想使用例如country1 某处的数据库,你只需要做

import { country1DB } from './databases';

country1DB.User.findAll({...});

以上代码将在先前指定的country1 数据库中执行SELECT * FROM users。示例 express 路线如下所示:

import * as databases from './databases';

app.get('/:dbIndex/users', (req, res) => {
    databases['country' + req.params.dbIndex + 'DB'].User.find().then(user => {
        res.json(user.toJSON());
    });
});

或者,更好的是,您可以编写一些中间件函数,它会在每个请求之前运行,并负责为进一步的操作选择合适的数据库。

关于node.js - Sequelize : connect to database on run time based on the request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42780489/

相关文章:

java - Hibernate一级缓存的使用

java - 使用 JPA 和 MySQL 检查用户是否喜欢该帖子的最佳方法是什么?

javascript - Nodejs 处理上传的文件

json - 列表中的 Postgres JSON 查询

sockets - 在 node.js 中使用 net.createConnection(port, [host]) 创建一个 tcp 套接字

sql - 如果不是今天的日期,则条件查询返回时间戳,否则返回时间

postgresql - 事务上下文中 postgres 日志中 "execute"和 "statement"之间的差异

javascript - coupon.getItemTypes() 不是属于ToMany 的函数

javascript - 使用 Node.JS 进行实时图形处理

linux - 在 npm install -g 之后尝试运行时没有这样的文件或目录