gpt4 book ai didi

javascript - 如何通过Sequelize连接多个数据库?

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:59 25 4
gpt4 key购买 nike

我需要根据 Express 路线连接到不同的数据库。

例如:

example.com/oneapp该路由必须访问名为 oneapp 的数据库

example.com/secondapp该路由必须访问名为 secondaryapp 的数据库

我的 Sequelize 中有这些设置

index.js:

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const config = require('../../config/database.js');

const db = {};
const sequelize = new Sequelize(config.producao);

fs
.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== path.basename(__filename)) && (file.slice(-3) === '.js'))
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});


console.log(db)

Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

数据库.js

module.exports = {
"producao": {
username: 'sa',
password: 'mypass',
database: 'PRODUCAO',
host: 'SVRNAZ002',
dialect: 'mssql',
}
}

最佳答案

使用不同的数据库设置运行该代码两次,并保留两组sequelize连接对象和模型数组。

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const configs = [require('../../config/database.js'), require('../../config/database2.js')];

module.exports = configs.map(config => {

const db = {};
const sequelize = new Sequelize(config.producao);

// load stuff like normal

db.sequelize = sequelize;
db.Sequelize = Sequelize;

return db;

});

现在您可以访问两者:

const models = require('index');

const firstdb = models[0];
const seconddb = models[1];

关于javascript - 如何通过Sequelize连接多个数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57503085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com