typescript - How to use the same sequelize's model but as it was a different instance? - Stack Overflow

admin2025-04-15  3

I use Sequelize v6.x with Typescript.

My model :

class Book extends Model<InferAttributes<Book>, InferCreationAttributes<Book>> {
  declare ID    : number;
  declare Title : string;

  declare test? : NonAttribute<number>;
  
}


export function initModel(sequelize: Sequelize): typeof Book {
  Book.init(
    {
      ID: {
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true
      },
      Title: {
        type: DataTypes.STRING(31),
        allowNull: true,
        defaultValue: ""
      }
    }, {
      sequelize,
      tableName: 'Book',
      timestamps: false,
      indexes: [
        {
          name: "PRIMARY",
          unique: true,
          using: "BTREE",
          fields: [
            { name: "ID" },
          ]
        },
      ]
   }
  );
  return Book;
}

I use 2 different databases. So I use 2 database connections :

// First database connection
const sequelize1 = new Sequelize({
  database: 'database1',
  username: 'user1',
  password: 'password1',
  host: 'localhost',
  dialect: 'mysql'
});

// Second database connection
const sequelize2 = new Sequelize({
  database: 'database2',
  username: 'user2',
  password: 'password2',
  host: 'localhost',
  dialect: 'mysql'
});

Then I initialize the models separately.

const bookModel1 = initModel(sequelize1);
const bookModel2 = initModel(sequelize2);

So, bookModel1 is connected to the database 1 and bookModel2 is connected to the database 2.

The problem is the following :

bookModel1.test = 123;
bookModel2.test = 456;
console.log(bookModel1.test);   // Print '456' instead of '123';
console.log(bookModel2.test);   // Print '456'

I would like the Book class to be a different instance for each model. How can I do that ?

Thanks for your help.

转载请注明原文地址:http://www.anycun.com/QandA/1744730634a86818.html