gpt4 book ai didi

node.js - 一个带有 Node js 的应用程序,每个客户端不同的数据库

转载 作者:可可西里 更新时间:2023-11-01 10:48:57 25 4
gpt4 key购买 nike

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

例如:

  • Application nodejs running on localhost: 3001

  • Mongo server running at localhost: 27017

  • A client (CLIENT1) accesses the nodejs application and modifies data in its database -> localhost:27017/client1

  • Another client (CLIENT2) does the same and accesses the application nodejs but modifies its data in localhost:27017/client2

对于每个注册该应用程序的客户,依此类推。

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

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

索引.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!');
});

演示模型.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 创建的

enter image description here

最佳答案

您要做的是制作一个 Multi-Tenancy nodejs 应用程序。

您采用的方法有一些缺点:

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

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

我有同样的问题并写了一个blog post关于它。

关于node.js - 一个带有 Node js 的应用程序,每个客户端不同的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45550906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com