我正在try 创建一个多租户应用程序(saas),每个客户端都有自己的数据库.

我的情况是:

我创建了一个中间件,可以根据子域确定客户机是谁,然后从通用数据库中检索客户机的数据库连接信息.我不知道如何为此客户端建立连接对象,以便能够在我的控制器中使用.我应该在中间件中还是在控制器中这样做?如果它在模型中,我如何传递连接字符串和参数(我可以使用会话,但我不知道如何从模型中访问会话).

我如何做到以下几点?

  1. 组织:我在哪里为客户创建数据库连接?
  2. 将连接参数注入/传递到控制器或模型(在其中定义连接)
  3. 建立动态连接后,如何为该客户端全局访问它?

这是我的中间件的一个例子,我想创建一个mongoose连接,我想使其动态(传入客户端的连接信息):

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 && req.session.Client.name === req.subdomains[0]) {
          var options = session.Client.options;
          var url = session.Client.url
          var conn = mongoose.createConnection(url, options);
          next();
       }
    }
}

如何从控制器内部访问此连接对象?还是模特?

非常感谢.

推荐答案

这是为了帮助其他人,他们可能会发现自己处于与我类似的情况.我希望它能标准化.我不认为每次有人需要开发多租户应用程序时,我们都需要重新设计轮子.

本例描述了一种多租户 struct ,每个客户机都有自己的数据库.

以下是本解决方案的目标:

  • 每个客户端都由子域标识,例如client1.应用通用域名格式,
  • 应用程序判断子域是否有效,
  • 应用程序从主数据库中查找并获取连接信息(数据库url、凭据等),
  • 应用程序连接到客户端数据库(基本上交给客户端),
  • 应用程序采取措施确保完整性和资源管理(例如,对同一客户端的成员使用相同的数据库连接,而不是建立新连接).

这是密码

在你的app.js档案里

app.use(clientListener()); // checks and identify valid clients
app.use(setclientdb());// sets db for valid clients

我创建了两个中间件:

  • clientListener-要识别正在连接的客户端,
  • setclientdb-在识别客户机后,从主数据库获取客户机详细信息,然后建立到客户机数据库的连接.

clientListener中间件

我通过判断请求对象的子域来判断客户机是谁.我做了一系列判断以确保客户机是有效的(我知道代码很乱,可以更干净).确保客户端有效后,我将客户端信息存储在会话中.我还判断,如果客户端信息已经存储在会话中,则无需再次查询数据库.我们只需要确保请求子域与会话中已存储的子域相匹配.

var Clients = require('../models/clients');
var basedomain = dbConfig.baseDomain;
var allowedSubs = {'admin':true, 'www':true };
allowedSubs[basedomain] = true;
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.subdomains[0] in allowedSubs ||  typeof req.subdomains[0] === 'undefined' || req.session.Client && req.session.Client.name === req.subdomains[0] ){
        //console.dir('look at the sub domain  ' + req.subdomains[0]);
        //console.dir('testing Session ' + req.session.Client);
        console.log('did not search database for '+ req.subdomains[0]);
        //console.log(JSON.stringify(req.session.Client, null, 4));
        next();
    }
    else{

        Clients.findOne({subdomain: req.subdomains[0]}, function (err, client) {
            if(!err){
                if(!client){
                    //res.send(client);
                    res.send(403, 'Sorry! you cant see that.');
                }
                else{
                    console.log('searched database for '+ req.subdomains[0]);
                    //console.log(JSON.stringify(client, null, 4));
                    //console.log(client);
                   // req.session.tester = "moyo cow";
                    req.session.Client = client;
                    return next();

                }
            }
            else{
                console.log(err);
                return next(err)
            }

        });
    }

   }
 }

module.exports = clientlistener;

setclientdb中间件:

我再次判断所有内容,确保客户有效.然后,使用从会话检索到的信息打开与客户机数据库的连接.

我还确保将所有活动连接存储到一个全局对象中,以防止每次请求时都有新的数据库连接(我们不想让每个客户端mongodb服务器的连接过载).

var mongoose = require('mongoose');
//var dynamicConnection = require('../models/dynamicMongoose');
function setclientdb() {
    return function(req, res, next){
        //check if client has an existing db connection                                                               /*** Check if client db is connected and pooled *****/
    if(/*typeof global.App.clientdbconn === 'undefined' && */ typeof(req.session.Client) !== 'undefined' && global.App.clients[req.session.Client.name] !== req.subdomains[0])
    {
        //check if client session, matches current client if it matches, establish new connection for client
        if(req.session.Client && req.session.Client.name === req.subdomains[0] )
        {
            console.log('setting db for client ' + req.subdomains[0]+ ' and '+ req.session.Client.dbUrl);
            client = mongoose.createConnection(req.session.Client.dbUrl /*, dbconfigoptions*/);


            client.on('connected', function () {
                console.log('Mongoose default connection open to  ' + req.session.Client.name);
            });
            // When the connection is disconnected
            client.on('disconnected', function () {
                console.log('Mongoose '+ req.session.Client.name +' connection disconnected');
            });

            // If the Node process ends, close the Mongoose connection
            process.on('SIGINT', function() {
                client.close(function () {
                    console.log(req.session.Client.name +' connection disconnected through app termination');
                    process.exit(0);
                });
            });

            //If pool has not been created, create it and Add new connection to the pool and set it as active connection

            if(typeof(global.App.clients) === 'undefined' || typeof(global.App.clients[req.session.Client.name]) === 'undefined' && typeof(global.App.clientdbconn[req.session.Client.name]) === 'undefined')
            {
                clientname = req.session.Client.name;
                global.App.clients[clientname] = req.session.Client.name;// Store name of client in the global clients array
                activedb = global.App.clientdbconn[clientname] = client; //Store connection in the global connection array
                console.log('I am now in the list of active clients  ' + global.App.clients[clientname]);
            }
            global.App.activdb = activedb;
            console.log('client connection established, and saved ' + req.session.Client.name);
            next();
        }
        //if current client, does not match session client, then do not establish connection
        else
        {
            delete req.session.Client;
            client = false;
            next();
        }
    }
    else
    {
        if(typeof(req.session.Client) === 'undefined')
        {
           next();
        }
        //if client already has a connection make it active
        else{
            global.App.activdb = global.App.clientdbconn[req.session.Client.name];
            console.log('did not make new connection for ' + req.session.Client.name);
            return next();
        }

    }
    }
}

module.exports = setclientdb;

最后但并非最不重要

因为我使用的是mongoose和原生mongo的组合,所以我们必须在运行时编译我们的模型.请看下面

把这个加到你的app.js

// require your models directory
var models = require('./models');

// Create models using mongoose connection for use in controllers
app.use(function db(req, res, next) {
    req.db = {
        User: global.App.activdb.model('User', models.agency_user, 'users')
        //Post: global.App.activdb.model('Post', models.Post, 'posts')
    };
    return next();
});

说明:

正如我前面所说,我创建了一个全局对象来存储活动数据库连接对象:global.App.activdb

然后,我使用这个连接对象创建(编译)mongoose模型,然后将其存储在req对象的db属性中:req.db.我这样做是为了在我的控制器中访问我的模型,例如.

我的用户控制器示例:

exports.list = function (req, res) {
    req.db.User.find(function (err, users) {

        res.send("respond with a resource" + users + 'and connections  ' + JSON.stringify(global.App.clients, null, 4));
        console.log('Worker ' + cluster.worker.id + ' running!');
    });

};

我最终会回来清理的.如果有人想帮我,那就太好了.

Mongodb相关问答推荐

用其他集合中的文档替换嵌套文档数组中的值

如何在MongoDB中通过限制和跳过查找项进行匹配

Mongoose 排除数组中包含特定嵌套对象的文档

从 kubectl exec 获取返回值到 powershell 脚本

使用名为 Object 键的 uuid 创建 mongodb 文档

为什么使用整数作为 pymongo 的键不起作用?

使用 Flask-pymongo 扩展通过 _id 在 MongoDB 中搜索文档

Mongoexport 在日期范围内使用 $gt 和 $lt 约束

Node.js 和 MongoDB,重用 DB 对象

如何更新 mongodb 文档以向数组添加新元素?

$elemMatch 的 MongoDB 索引

在 mongodb 中查找字段的所有非不同值

RoR3 上的 Mongoid:1)如何在查询中返回特定字段? 2)需要什么 inverse_of ?

MongoDb 数据库与集合

mongodb启动错误

Java Mongodb 正则表达式查询

未找到 MongoDB 数据/数据库

Meteor 发布/订阅独特客户端集合的策略

哪个数据库适合我的应用程序 mysql 或 mongodb ?使用 Node.js 、 Backbone 、 Now.js

findOneAndUpdate 中的文档未更新