使用 Sequelize 连接到 Feathers.js 中的多个 MySQL 数据库

Luc*_*ert 3 mysql node.js express sequelize.js feathersjs

我一直无法找到使用 Sequelize 连接 Feathers.js 中多个 MySQL 数据库的记录方法。有没有办法做到这一点?我的用例是能够通过同一操作将数据行插入和获取到多个数据库中,但数据库不一定是相同的架构。

谢谢!

小智 5

我在本地做了一些测试,是可以的。您需要定义 2 个不同的续集客户端。如果您使用 CLI 生成器并且设置了基于 Sequelize 的服务,您应该有一个连接字符串(我的示例是 mysql 数据库):

  • config/default.json 中的数据库连接字符串

    "mysql" : "mysql://user:password@localhost:3306/your_db"

  • sequelize.jssrc根文件夹中的a

为了创建第二个续集客户端

  1. 在中创建一个新的连接字符串config/default.json

    "mysql2" : "mysql://user:password@localhost:3306/your_db_2"

  2. 创建sequelize.js 的副本并为其命名sequelize2.js

    const Sequelize = require('sequelize');

    module.exports = function (app) {
      const connectionString = app.get('mysql2');
      const sequelize2 = new Sequelize(connectionString, {
        dialect: 'mysql',
        logging: false,
        operatorsAliases: false,
        define: {
          freezeTableName: true
        }
      });
      const oldSetup = app.setup;
    
      app.set('sequelizeClient2', sequelize2);
    
      app.setup = function (...args) {
        const result = oldSetup.apply(this, args);
    
        // Set up data relationships
        const models = sequelize2.models;
        Object.keys(models).forEach(name => {
          if ('associate' in models[name]) {
            models[name].associate(models);
          }
        });
    
        // Sync to the database
        sequelize2.sync();
    
        return result;
      };
    };
    
    Run Code Online (Sandbox Code Playgroud)

将新的sequelize 配置添加到您的app.js

const sequelize2 = require('./sequelize2');
app.configure(sequelize2);
Run Code Online (Sandbox Code Playgroud)

然后在你的模型中到第二个数据库:

const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;

module.exports = function (app) {
  //load the second client you defined above
  const sequelizeClient = app.get('sequelizeClient2');
  //to check if connect to a different db
  console.log ( sequelizeClient )
  //your model
  const tbl = sequelizeClient.define('your_table', {

    text: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    hooks: {
      beforeCount(options) {
        options.raw = true;
      }
    }
  });

  // eslint-disable-next-line no-unused-vars
  tbl.associate = function (models) {
    // Define associations here
    // See http://docs.sequelizejs.com/en/latest/docs/associations/
  };

  return tbl;
};
Run Code Online (Sandbox Code Playgroud)

为了工作,您需要 2 个不同的服务,每个服务使用不同的数据库。如果您想通过单个操作进行放置或获取,您可以在其中一个服务中创建一个 before/after 挂钩,并在挂钩内调用第二个服务。对于 get,您需要将第二个服务的结果添加到您的挂钩结果中