Saturday 11 March 2017

Sequelize and Node.js: Initializing Multiple Databases On One Server Programmatically

When I run the server attempting to create two databases (db1 and db2), the system kicks backs this error:

Possibly unhandled SequelizeBaseError: database "db2" does not exist

As a reference, there is similar stackoverflow question on this topic here, however, the author of the solution does not cover the solution to how the server.js file is setup. You will notice I have structured my index.js file similar to their answer.

My models/index.js file and server run and executes scripts properly, yet the second database does not work at all and does not even get initialized.

Can someone provide a solution for the server.js file to accurately initialize two databases in this one server?

The following is the partial code from the models/index.js and server.js files. In the server.js file, I am using .sync to initialize the databases.

models/index.js

    var databasesArray = ['db1', 'db2']
    var databasesObj = {
        database: {
            db1: {
                DBName: 'db1',
                User: user,
                Password: password,
                Config: config,
            },
            db2: {
                DBName: 'db2',
                User: user,
                Password: password,
                Config: config,
            }
        }
    } // EOF databaseObj                                                                                                                                                                     

    for(var i = 0; i < databasesArray.length; ++i) {
        var databasePointerToOBJ = databasesArray[i];
        var database = databasesObj.database[databasePointerToOBJ]
        if(database.DBName == 'db1'){
            var sq = new Sequelize(database.DBName, user, password, config)
            db['db1'] = {
                Sequelize: Sequelize,
                sequelize: sq,
                Table1: sq.import(__dirname + '/...')
            }
        }else if(database.DBName == 'db2'){
            var sq = new Sequelize(database.DBName, user, password, config)
            db['db2'] = {
                Sequelize: Sequelize,
                sequelize: sq,
                Table1: sq.import(__dirname + '/...')
            }
        }
    }
module.exports = db;

server.js

    [...] 
    //sync's sequelize DB tables                                                                                                                                                                     
    db['db1'].sequelize.sync(function(err){});
    db['db2'].sequelize.sync(function(err){});



via JMM

No comments:

Post a Comment