【问题标题】:How can I Connect a Postgres Schema in Nodejs and Switching Schemas Dynamically Using Sequelize?如何在 Nodejs 中连接 Postgres 模式并使用 Sequelize 动态切换模式?
【发布时间】:2020-08-03 02:24:29
【问题描述】:

我必须连接到 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)
}

收到回复后,我必须根据上述结果动态切换架构

请大家帮帮我

【问题讨论】:

标签: sql node.js postgresql schema


【解决方案1】:

我使用 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}'`
        )

【讨论】:

    猜你喜欢
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2017-01-27
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多