mysql Sequelize:使用不同的模式/模型连接多个数据库

dojqjjoe  于 2023-01-08  发布在  Mysql
关注(0)|答案(1)|浏览(225)

有两个数据库。不能对不同的数据库使用不同的架构。验证成功后。如何连接不同的架构/模型?
1.

posAdminDB.users = require("../models/user/user")(sequelize, DataTypes);

1.则错误:

***/models/user/user.js:2
  const User = sequelize.define("user", {
                         ^
TypeError: Cannot read properties of undefined (reading 'define')

用户模型

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define("user", {
    name: {
      type: DataTypes.STRING,
    },
  });
  return User;
};
    • 配置:**

数据库:1

mainDB = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
    dialect: dbConfig.DIALECT,
    host: dbConfig.HOST,
    port: dbConfig.PORT,
    define: {
        timestamps: false,
    },
    operatorsAliases: 0,
    pool: {
        max: dbConfig.pool.max,
        mix: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle,
    },
});

数据库:2

posAdminDB = new Sequelize(adminDB.DB, adminDB.USER, adminDB.PASSWORD, {
    dialect: adminDB.DIALECT,
    host: adminDB.HOST,
    port: adminDB.PORT,
    define: {
        timestamps: false,
    },
    operatorsAliases: 0,
    pool: {
        max: adminDB.pool.max,
        mix: adminDB.pool.min,
        acquire: adminDB.pool.acquire,
        idle: adminDB.pool.idle,
    },
});

认证

mainDB.Sequelize = Sequelize;
mainDB.sequelize = sequelize;

posAdminDB.Sequelize = Sequelize;
posAdminDB.sequelize = sequelize;

try {
    mainDB.authenticate().then(() => {
        console.log("Connection has been established with DB:1 successfully");
    });
    posAdminDB.authenticate().then(() => {
        console.log("Connection has been established with DB:2 successfully");
    });
} catch (error) {
    console.error("Unable to connect to the database:", error);
}

认证没有错误

    • 验证输出:**

第一个月
Executing (default): SELECT 1+1 AS result
Executing (default): SELECT 1+1 AS result
Connection has been established with DB:2 successfully
Connection has been established with DB:1 successfully

2ul0zpep

2ul0zpep1#

您应该将正确的Sequelize示例传递给特定的模型配准函数:

posAdminDB.users = require("../models/user/user")(posAdminDB.sequelize, DataTypes);
mainDB.users = require("../models/user/user")(mainDB.sequelize, DataTypes);

相关问题