如何在 NodeJS 中创建多个数据库 sequelize 会话
How to create multiple database sequelize sessions in NodeJS
我正在使用无服务器框架创建后端 API,在该框架中我将 Nodejs 与 Sequelize 结合使用。我的方言是 postgresql。我需要同时与两个数据库进行交互并保持会话。
我做的是这个
我的文件夹结构是
- 回购
- 数据库 1
- model1.js
- 数据库 2
- model2.js
const db = {};
const DBs = DB_NAME.split(',');
console.log(DB_NAME);
console.log(DBs);
for(let i = 0; i < DBs.length; ++i) {
let database = DBs[i];
//Store the database connection in our db object
db[database] = new Sequelize(database, DB_USERNAME, DB_PASSWORD, {
host: DB_HOSTNAME,
port: DB_PORT,
dialect: DB_DIALECT,
pool: {
max: 10,
min: 1,
idle: 20000,
acquire: 20000,
},
define: {
underscored: true,
timestamps: true,
paranoid: true,
},
});
}
这运行良好。但是当我尝试添加模型时
fs
.readdirSync(__dirname + '/product')
.filter(file =>
(file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js'))
.forEach(file => {
const model = db.product.import(path.join(__dirname + '/product', file));
db.[model.name] = model;
});
// Add models from database2 folder
fs
.readdirSync(__dirname + '/painted')
.filter(file =>
(file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js'))
.forEach(file => {
const model = db.painted.import(path.join(__dirname + '/painted', file));
db.[model.name] = model;
});
上面给出的错误是 import 不是 undefined
的函数
任何人都可以帮助我吗
我在将模型添加到 db 对象时出错。
而不是
db.[model.name] = model;
我需要做
db.painted.[model.name] = model;
和
db.product.[model.name] = model;
因此。
一切正常。我可以在每个 API 调用
上保持两个会话
我正在使用无服务器框架创建后端 API,在该框架中我将 Nodejs 与 Sequelize 结合使用。我的方言是 postgresql。我需要同时与两个数据库进行交互并保持会话。
我做的是这个 我的文件夹结构是
- 回购
- 数据库 1
- model1.js
- 数据库 2
- model2.js
const db = {};
const DBs = DB_NAME.split(',');
console.log(DB_NAME);
console.log(DBs);
for(let i = 0; i < DBs.length; ++i) {
let database = DBs[i];
//Store the database connection in our db object
db[database] = new Sequelize(database, DB_USERNAME, DB_PASSWORD, {
host: DB_HOSTNAME,
port: DB_PORT,
dialect: DB_DIALECT,
pool: {
max: 10,
min: 1,
idle: 20000,
acquire: 20000,
},
define: {
underscored: true,
timestamps: true,
paranoid: true,
},
});
}
这运行良好。但是当我尝试添加模型时
fs
.readdirSync(__dirname + '/product')
.filter(file =>
(file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js'))
.forEach(file => {
const model = db.product.import(path.join(__dirname + '/product', file));
db.[model.name] = model;
});
// Add models from database2 folder
fs
.readdirSync(__dirname + '/painted')
.filter(file =>
(file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js'))
.forEach(file => {
const model = db.painted.import(path.join(__dirname + '/painted', file));
db.[model.name] = model;
});
上面给出的错误是 import 不是 undefined
的函数任何人都可以帮助我吗
我在将模型添加到 db 对象时出错。
而不是
db.[model.name] = model;
我需要做
db.painted.[model.name] = model;
和
db.product.[model.name] = model;
因此。
一切正常。我可以在每个 API 调用
上保持两个会话