Monday, 10 April 2017

How can I direct calls to different instance MongoDB based on logged in user?

I'm working on a project that will be a multi-tenant Saas application, and am having difficulty implementing a way to log into various databases depending on the user login info. Right now, I just want to split traffic between a Sandbox database (for demo purposes, and will be wiped on a regular basis), and an Alpha database (for current client testing and development). I have written the middleware below, config.js, that detects the user ID on login and assigns a database object using mongoose.createConnection(). This key-value pair is then added to a store using memory-cache. Here is the config.js code:

var mcache = require('memory-cache'),
    Promise = require("bluebird"),
    mongoose = require('mongoose');

Promise.promisifyAll(require("mongoose"));
(function () {

    'use strict';

    var dbSand = mongoose.createConnection(process.env.DB_SAND);
    var dbAlpha = mongoose.createConnection(process.env.DB_ALPHA);

    function dbPathConfigMiddlewareWrapper (){
        return function  setDbPath(req, res, next){
            if ( req ){
                if (!mcache.get(req.session.id) && req.body.email){
                    var login = req.body.email;
                    if (login === 'demo@mysite.com'){
                        mcache.put(req.session.id, dbSand);
                    } else {
                        mcache.put(req.session.id, dbAlpha);
                    }
                } 
                req.dbPath = mcache.get(req.session.id);

                next();
            }

        };

    }

module.exports = dbPathConfigMiddlewareWrapper;

}());

So far so good. But I have been unsuccessful in calling the correct database in my routes. When I was just using a single database, I could easily use this:

  var connStr = process.env.DBPATH;

  if(mongoose.connection.readyState === 0){
      mongoose.connect(connStr, function(err) {
          if (err) throw err;
          console.log('Successfully connected to MongoDB');
      });
    }

Now, I'm trying this to no avail:

  var connStr = req.dbPath;  //where req.dbPath is assigned in the config middleware above.

  if(connStr.connection.readyState === 0){
      mongoose.connect(req.dbPath, function(err) {
          if (err) throw err;
          console.log('Successfully connected to MongoDB');
      });
    }

Any guidance here would be greatly appreciated. This seems like it should be much more straightforward, and the documentation alludes to it but does not elaborate.



via espressoAndCode

No comments:

Post a Comment