title: Dynamic database connection to mongodb or mongoose from nodejs
body: <p>I am trying to create a multi-tenant app (saas), where each client has its own database.</p>
  
  <p>My situation is:</p>
  
  <p>I created a middleware that would determine who the client is based on a subdomain, then retrieve the client's database connection info from a general database. I don't know how to establish a connection object for this client so as to be able to use in my controllers. And should I do this in the middleware  or in a controller? And if it's in the model, how do i pass the connection string and parameters (I could use session, but I don't know how to access session from within model).</p>
  
  <p>How do i do the following?</p>
  
  <ol>
  <li>Organisation: where do I create the db connection for client dynamically?</li>
  <li>Inject/pass connection parameters to controller or model (where connection definition is made)</li>
  <li>After dynamic connection has been made, how do i access it globally for that client?</li>
  </ol>
  
  <p>This is an example of my middleware, and i would like to create a mongoose connection which i would like to make dynamic (pass in client's connection info):</p>
  
  <pre><code>function clientlistener() {
      return function (req, res, next) {
         console.dir('look at my sub domain  ' + req.subdomains[0]);
         // console.log(req.session.Client.name);
  
      if (req.session.Client &amp;&amp; req.session.Client.name === req.subdomains[0]) {
            var options = session.Client.options;
            var url = session.Client.url
            var conn = mongoose.createConnection(url, options);
            next();
         }
      }
  }
  </code></pre>
  
  <p>How do I access this connection object from inside the controller? Or from the model?</p>
  
  <p>Thank you.</p>