Using node.js, how can I write to one MySQL DB and read from another?

In particular, I'm talking about MySQL Master-Slave(s) Replication . As far as I understand, all my readings should come from a slave (or several slaves hidden behind a load balancer), and all my records are directly recorded to the master.

How can I do this using node.js ? I use the MySQL Active Record package for my database queries, and I don't think it supports it natively. I suggested that I could crack the package and have a type like if is write-query, then use db1 , but I'm wondering if there is an easier way.

+4
source share
1 answer

You can simply create two adapters, for example:

 var activeRecord = require('mysql-activerecord'); var readDB = new activeRecord.Adapter({ server: 'slave.db.com', username: 'user', password: 'pass', database: 'db' }); var writeDB = new activeRecord.Adapter({ server: 'master.db.com', username: 'user', password: 'pass', database: 'db' }); 

When you go to update or another write request, use writeDB ; when you go to use select , use readDB .

Another option would be to switch to another ORM that supports this out of the box. I know this is not so good for a solution. Sequelize , for example, is widely used and supports this out of the box.

+3
source

All Articles