Sequelize: Using Multiple Databases

前端 未结 3 511
Happy的楠姐
Happy的楠姐 2020-12-02 17:26

Do I need to create multiple instances of Sequelize if I want to use two databases? That is, two databases on the same machine.

If not, what\'s the proper way to do

相关标签:
3条回答
  • 2020-12-02 18:09

    You need to create different instances of sequelize for each DB connection you want to create:

    const Sequelize = require('Sequelize');
    const userDb = new Sequelize(/* ... */);
    const contentDb = new Sequelize(/* ... */);
    

    Each instance created from sequelize has its own DB info (db host, url, user, pass, etc...), and these values are not meant to be changed, so there is no "correct" way to create multiple connections with one instance of sequelize.

    From their docs:

    Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database.

    One instance per database

    A "common" approach to do this, is having your databases in a config.json file and loop over it to create connections dinamically, something like this maybe:

    config.json

    {
        /*...*/
        databases: {
            user: {
                path: 'xxxxxxxx'
            },
            content: {
                path: 'xxxxxxxx'
            }
        }
    }
    

    Your app

    const Sequelize = require('sequelize');
    const config = require('./config.json');
    
    // Loop through
    const db = {};
    const databases = Object.keys(config.databases);
    for(let i = 0; i < databases.length; ++i) {
        let database = databases[i];
        let dbPath = config.databases[database];
        db[database] = new Sequelize( dbPath );
    }
    
    // Or a one liner
    const db = Object.entries(config).reduce((r, db) => (r[db[0]] = db[1].path) && r, {});
    
    // Sequelize instances:
    // db.user
    // db.content
    

    You will need to do a little bit more coding to get it up and running but its a general idea.

    0 讨论(0)
  • 2020-12-02 18:12

    Why don't you use raw query? With this you can connect to one database and query the other. See sample code below.

    const sequelize = require('db_config');
    function test(req, res){
      const qry = `SELECT * FROM db1.affiliates_order co
    LEFT JOIN db2.affiliates m ON m.id = co.campaign_id`;
      sequelize.query(qry, null, {  raw: true}).then(result=>{
        console.log(result);
      })
    }
    
    0 讨论(0)
  • 2020-12-02 18:14

    if you are trying to associate objects in the same RDS across multiple databases, you can use schema.

    http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-schema

    this will prepend the db name to the table name so, presumably, your queries would come out like: SELECT A.ColA, B.ColB FROM SchemaA.ATable A INNER JOIN SchemaB.BTable B ON B.BId = A.BId

    0 讨论(0)
提交回复
热议问题