sql - 如何在 Nodejs 中连接 Postgres 模式并使用 Sequelize 动态切换模式?
问题描述
我必须连接到 Node.js 中的 Postgres 数据库,并且我想使用 Sequelize 库动态切换模式。
这是我的表模型和控制器代码。
module.exports = function (sequelize, DataTypes) {
const customer = sequelize.define(
'customer',
{
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
schema_name: {
type: DataTypes.STRING,
allowNull: false,
},
created_on: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW(),
},
},
{
schema: 'public',
}
)
return customer
}
和控制器代码
exports.login = async (req, res, next) => {
const { email, password, domain } = req.body
const domainData = await customer.findOne({
where: { schema_name: domain },
})
console.log('Log: exports.login -> domainData', domainData)
}
一旦收到响应,我必须根据上述结果动态切换模式。
请帮帮我
解决方案
我使用sequelize.query()函数解决了这个问题。
获取域...
const domainData = await sequelize.query(
`SELECT schema_name from public.customer_management_client where schema_name = '${domain}'`
)
用于切换到动态模式
const UserData = await sequelize.query(
`SELECT * from ${domainData[0][0].schema_name}.user_access_user where email = '${email}'`
)
推荐阅读
- python - 如何在 django 管理页面中修复下面的“请更正重复项”?
- java - Java - MySQL 执行存储过程
- flutter - 如何将 ColorFilter 矩阵应用于直接文件或图像并将其保存在颤动中?
- java - 如何将一堆数据添加到链表中
- java - E/AndroidRuntime: FATAL EXCEPTION: main 当我尝试运行并将一个片段连接到另一个片段时
- reactjs - 当我使用 :first-child in Emotion 时如何解决此错误
- ios - Xcode 框架中的混合语言文档生成
- android - 需要关于 onbackpressed 中的 CountDownTimer 的帮助
- mysql - 由 korth 从数据库系统概念创建 time_slot 表
- amazon-web-services - 允许 AWS Private EC2 HTTP 和 HTTPS 公开