I am getting the database name from front end when user logged in the system and I have to make the connection with that database for further process.I am able to do it if create the connection on same page but I want to use 'exports'
I am trying this. I am new in node.js so if there is some very silly mistake please dont mind and help me to understand.
I tried different way of exporting but not able to make it run.
my DB_dynamic.js:
var mysql = require('mysql');
exports.dynamicConnection= function(dbname){
var connection = mysql.createConnection({
host: process.env.DBHost || 'localhost',
port: process.env.DBPort || 3306,
user: process.env.DBUser || 'root',
password: process.env.DBPassword || '',
database: process.env.DBName || dbname
});
connection.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected...');
});
}
now in my model.js
var new_conn = require('./DB_dynamic.js');
var conn = new_conn.dynamicConnection(dbname);
conn.query("my query"); //Error!
Error:
TypeError: Cannot read property 'query' of undefined