【问题标题】:One app with nodejs, different datababase per client一个带有节点 js 的应用程序,每个客户端不同的数据库
【发布时间】:2018-01-14 23:53:48
【问题描述】:

我想使用 nodejs 创建一个应用程序,其中不同的公司/客户连接但使用不同的数据库。

例如:

  • 在本地主机上运行的应用程序nodejs:3001

  • Mongo 服务器在本地运行:27017

  • 客户端 (CLIENT1) 访问 nodejs 应用程序并修改数据 在其数据库中-> localhost:27017/client1

  • 另一个客户端 (CLIENT2) 执行相同操作并访问应用程序 nodejs 但在 localhost:27017/client2 中修改其数据

对于每个注册该应用程序的客户等等。

--------编辑----------

我一直在测试东西以获得我想要的东西,我想我已经想出了一个可能的解决方案。解决方案是为每个数据库访问创建一个连接。当您完成访问断开连接时。我不知道这是否是一个好的解决方案,但我认为值得:

index.js

var express = require('express');
var app = express();
var repository = require('./demoqueryrepository')

app.get('/createdb', function (req, res) {
    //TODO: With JWT decode get id client and pass like as param to repository
    repository.crearDemo(req.query.id, function (err, resp) {
        if (err) console.log(err)
        else res.send("resp");
    })
});


app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

demomodel.js

 var mongo = require('mongoose');
    var Schema = mongo.Schema;

    module.exports = mongo.model('demodto', new Schema({
        Name: { type: String },
        Code: { type: Number },

    }));

demoqueryrepository.js

var _demo = require('./demoquerydto');
var mongo = require('mongoose')
var mongoconnect = require('./mongoconnect')

module.exports = {
    crearDemo: function (idclient, callback) {
        let newdemo = new _demo({
            Name: " Demo " + idclient,
            Code: idclient
        })
        mongoconnect.connect(idclient);
        newdemo.save(function (error) {
            if (error) callback(error, null);
            else {
                callback(null, "success");
                mongo.disconnect();
            }
        })


    }
}

mongoconnect.js

var mongo = require('mongoose')

module.exports = {
    connect: function (idclient) {
        mongo.connect('mongodb://localhost:27017/' + idclient, { useMongoClient: true }, function (err, res) {
            if (err) console.log(err);
            else console.log("Connected to db")
        });
    }
}

当我发起请求时:

localhost:3000/createdb?id=12

localhost:3000/createdb?id=13

localhost:3000/createdb?id=14

在数据库服务器上,数据库是使用这些 id 创建的

【问题讨论】:

  • 您将如何通过名称/ID 找出不同的客户?不同客户端的 db 架构是否不同或类似?
  • 模式相似,识别不同客户端的目的是通过一个 id。例如,client1 的 id 为 198,将使用该名称创建数据库

标签: node.js mongodb mongoose


【解决方案1】:

您要做的是制作一个多租户 nodejs 应用程序。

您所采用的方法几乎没有缺点:

  • 用户 ID 有一个通用数据库,它将告诉连接到哪个数据库,然后每个客户端一个。这意味着您有 n+1 连接。
  • 您的应用程序将无法扩展,因为您总是会过度配置/配置不足的数据库,或者更糟糕的是为每个新客户加入部署更改。

您是否考虑过只有一个数据库,因为架构是相同的?如果您为每个客户端设置默认搜索范围,则可以解决一个客户端必须访问数据的常见担忧。

我遇到了同样的问题,并为此写了blog post

【讨论】:

  • 我已决定使用单个 mongo 数据库。我读了这篇文章,你使用了 sequelize,它必须改变很多已经实现的东西。因此,我将使用数据库来照顾并考虑客户的 ID。感谢您的回答,我认为它是有效的,因为它让我思考。
猜你喜欢
  • 2020-03-14
  • 2016-11-23
  • 2017-05-03
  • 2018-07-13
  • 2015-04-14
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
相关资源
最近更新 更多