0

How to define a single model and associate with multiple database in sequelize?

Currently have a working application on node, using sequelize, connected to a mysql db, which is initialised as below

import { Sequelize } from 'sequelize'

const sequelize = new Sequelize(
  process.env.MYSQL_DB,
  process.env.MYSQL_USER,
  process.env.MYSQL_PASSWORD,
  {
    pool: {
      max: 30,
      min: 3,
      acquire: 60000, // throw error after 60s can not open connection
      idle: 10000 // release after 10s
    },
    dialect: 'mysql',
    host: process.env.MYSQL_HOST,
    port: process.env.MYSQL_PORT,
    logging: false
  }
)

export default sequelize

I now need to add another database, which is going to be the exact copy of the already existing database, calling it a sandbox

I know that sequelize can have multiple databases connected to it, which is what i require, and i am successfully able to do that.

The question is regarding the already defined models, and how those models would be associated with both the databases.

Currently the models are defined as such

import Sequelize, { Model } from 'sequelize'
import { sequelize } from '../configs'

class Job extends Model {
  slug: string
  httpData: string
}

Job.init(
  {
    id: {
      type: Sequelize.BIGINT({ length: 20, unsigned: true }),
      primaryKey: true,
      autoIncrement: true
    },
    name: { type: Sequelize.TEXT },
    slug: { type: Sequelize.CHAR(255) },
    group: { type: Sequelize.CHAR(16) },
    status: { type: Sequelize.CHAR(8) },
    httpStatus: { type: Sequelize.CHAR(3) },
    httpData: { type: Sequelize.TEXT({ length: 'long' }) },
    completed_at: { type: Sequelize.DATE }
  },
  {
    sequelize,
    tableName: 'stats_jobs',
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
)

export default Job

I don't feel like creating an exact copy of the above model to associate it with the sandbox is the right way to go, as it would create more complexities.

The main idea is whatever gets added in the main database, we have an exact copy of it in the sandbox database as well.

Hammad Khalid
  • 538
  • 3
  • 7
  • 21

1 Answers1

0

I suppose you should define models using Sequelize.define and return a model registering function from a model module.

See my answer about how to register all models and associations. That way you can register and store models for each connection into a separate object holding a connection itself and all its models.

Anatoly
  • 20,799
  • 3
  • 28
  • 42