livealvi
livealvi

Reputation: 601

Sequelize: Connect multiple databases with the Different schema/model

There are two databases. Couldn't use different schema for different databases. After authenticating successfully. How to connect different schema/model?

1.

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

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

user model

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

Configuration:

DB: 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,
    },
});

DB: 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,
    },
});

Authenticate

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);
}

There is no error in authenticating

authenticate output:
server is running port 8080
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

Upvotes: 1

Views: 231

Answers (1)

Anatoly
Anatoly

Reputation: 22758

You should pass a correct Sequelize instance to a certain model registration function:

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

Upvotes: 1

Related Questions