使用Sequelize连接Feathers.js中的多个MySQL数据库
我在Feathers.js中找不到使用Sequelize连接多个MySQL数据库的文档化方法。有办法做到这一点吗?我的用例是能够从同一个操作向多个数据库插入和获取数据行,但这些数据库不一定是同一个模式使用Sequelize连接Feathers.js中的多个MySQL数据库,mysql,node.js,express,sequelize.js,feathersjs,Mysql,Node.js,Express,Sequelize.js,Feathersjs,我在Feathers.js中找不到使用Sequelize连接多个MySQL数据库的文档化方法。有办法做到这一点吗?我的用例是能够从同一个操作向多个数据库插入和获取数据行,但这些数据库不一定是同一个模式 谢谢 我做了一些局部测试,这是可能的。您需要定义两个不同的sequelize客户端。 如果您正在使用CLI生成器并基于sequelize设置服务,则应该有一个连接字符串(我的示例是mysql db): config/default.json中的db连接字符串 “mysql”:mysql://us
谢谢 我做了一些局部测试,这是可能的。您需要定义两个不同的sequelize客户端。 如果您正在使用CLI生成器并基于sequelize设置服务,则应该有一个连接字符串(我的示例是mysql db):
- config/default.json中的db连接字符串
“mysql”:mysql://user:password@localhost:3306/your_db“
- src根文件夹中的
sequelize.js
config/default.json
“mysql2”:mysql://user:password@localhost:3306/your_db_2“
sequelize2.js
const Sequelize=require('Sequelize')
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;
};
为了工作,您需要两个不同的服务,每个服务使用不同的数据库。
如果您想通过单个操作放置或获取,您可以在其中一个服务中创建一个before/after钩子,并在钩子内部调用第二个服务。
对于get,您需要将第二次服务的结果添加到钩子结果中
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;
};