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

问题描述 投票:0回答:1

我一直无法找到使用Sequelize连接到Feathers.js中多个MySQL数据库的文档化方法。有没有办法做到这一点?我的用例是能够从同一个动作插入和获取数据行到多个DB,但DB不一定是相同的模式。

谢谢!

mysql node.js express sequelize.js feathersjs
1个回答
2
投票

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

  • config / default.json中的db连接字符串 "mysql" : "mysql://user:password@localhost:3306/your_db"
  • src根文件夹中的sequelize.js

为了创建第二个sequelize客户端

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

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

const sequelize2 = require('./sequelize2');
app.configure(sequelize2);

然后在你的模型中第二个db:

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

为了工作,您需要2个不同的服务,每个服务使用不同的数据库。如果你想放置或获得单个动作,你可以在其中一个服务中创建一个前/后挂钩,并在钩子内调用第二个服务。对于get,您需要将第二个服务的结果添加到钩子结果中

© www.soinside.com 2019 - 2024. All rights reserved.