栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

动态数据库连接到NodeJS的mongodb或mongoose

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

动态数据库连接到NodeJS的mongodb或mongoose

这是为了帮助其他可能会遇到与我类似情况的人。我希望它可以被标准化。我认为,每当有人需要进行多租户应用程序时,我们都不必重新发明轮子。

此示例描述了一个多租户结构,每个客户端都有自己的数据库。就像我说的那样,可能会有更好的方法,但是因为我自己没有得到帮助,所以这就是我的解决方案。

因此,此解决方案的目标是:

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

这是代码

在您的

app.js
文件中

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

我创建了两个中间件:

  • clientListener
    -识别连接的客户端,
  • setclientdb
    -在识别客户端之后,从Master数据库获取客户端详细信息,然后建立与客户端数据库的连接。

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            if( 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 ); 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;

最后但是同样重要的

由于我使用的是猫鼬和本地mongo的组合,因此我们必须在运行时编译模型。请看下面

将此添加到您的

app.js

// require your models directoryvar models = require('./models');// Create models using mongoose connection for use in controllersapp.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

然后,在将其存储在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!');    });};

我会回来并最终将其清理干净。如果有人想帮助我,那很好。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484887.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号