简体   繁体   中英

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.

server.js

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

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;

--- EDIT ---

The author of the solution was correct. In order for a new database to be created, it must be created prior to being sync'd. As piotrbienias rightly notes, adding the code for adding a new DB in a your initialization script would be the best option. Piotrbienias solution is .js option. The code that worked for me is a .sh option and is as following:

PG_HOST=localhost
PG_PORT=5432
PG_DB=databaseName
PG_USER=ubuntu
PG_PASS='EnterPassword'

sudo -u postgres createdb -U postgres -O $PG_USER $PG_DB

You need to create the database manually before trying to access it via Sequelize - it does not create it if it does not exists. You can use a pg module inside some initialisation script to create the DB via CREATE DATABASE before doing any synchronisation and connection, or simply create it via postgres CLI

const pg = require('pg');

module.exports = function(next){

    var connectionData = {
        user: 'postgres',
        password: 'password',
        host: 'localhost'
    };

    var databaseName = 'db2';
    var connectionUri = `postgres://${user}:${password}@${host}/postgres`;

    pg.connect(connectionUri, function(err, client, done) {
        client.query(`CREATE DATABASE ${databaseName}`, function(error){
            // here you can perform some sequelize operations after creating the database
            client.end(); // disconnect client
            next(); // you can call it with some parameter like Sequelize instance etc.
        });
    });

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM