首页 > 解决方案 > 如何在 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)
}

一旦收到响应,我必须根据上述结果动态切换模式。

请帮帮我

标签: sqlnode.jspostgresqlschema

解决方案


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

推荐阅读