Sequelize:根据请求在运行时连接数据库

3
我正在开发一个node.js应用程序,需要连接多个数据库。其中一个数据库是中央数据库,包含所有信息的共同点。然后有按国家存储数据的国家级数据库。
我在应用程序中使用sequelize ORM。
数据库是postgresql。
框架是express。
问题是我想根据请求在运行时决定要使用哪个数据库,并且模型应自动连接到适当的数据库。我看过this问题,但没有找到有用的信息。
我还在其他论坛上检查过,但没有找到任何有用的信息。

你所提到的问题实际上是对你问题的回答。为什么你觉得它没有帮助呢? - piotrbienias
我尝试在我的代码中使用相同的方法,但是我没有成功地使用模型绑定到数据库。 - Jitender Singla
1个回答

3

您需要创建与您的每个数据库对应的对象,并在每个对象中实例化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());
    });
});

或者,更好的方法是编写一些中间件函数,在每个请求之前运行,并负责选择适当的数据库进行进一步操作。

感谢@piotrbienias的回复。我会在我的应用程序中尝试这个解决方案,并会在状态更新后回复。 - Jitender Singla
我已经尝试过这个解决方案。我没有使用相同的代码。但是你的概念是正确的。我需要进行修改,现在它可以运行了。 - Jitender Singla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接