if(typeof clientdbconn === 'undefined'){
console.log('before init2 client conn ' + clientdbconn);
app.use(function(req, res, next){
if(req.session.Client && req.session.Client.name === req.subdomains[0] ){
var client = mongoose.createConnection(req.session.Client.dbUrl /*, dbconfigoptions*/);
client.on('connected', function () {
console.log('Mongoose default connection open to Client');
});
clientdbconn = client;
console.log('client connection established, and saved ' + clientdbconn);
next();
}
else{
delete req.session.Client;
client = false;
next();
}
});
}Enter code here...
3. created model with reference to the above connection (clientdbconn)
usersmodel
= new Schema({
name : String
});
User: clientdbconn.model('User', usersmodel, 'users');
This Partially works, in that the connection is made to the database and i can query. The problem is that on every request, a new connection is made. ( does not take advantage of persistence pooling).
I tried to store the connection outside of the middle ware in my app.js as a variable object like this
var clientdbconn;
and if you look at the middleware above I store the connection in the var clientdbconn;
But even after doing that, upon a new request the var clientdbconn; is set to undefined there fore making the middleware to create a new db connection.
Please what is the proper way to do this ?
create a new database connection during run time, and storing the connection for subsequent requests so as not to create new connections on every request unless the connection string changes.
Thanks in advance