Node.js 一个带有nodejs的应用程序,每个客户端有不同的数据库
我想用NodeJ创建一个应用程序,不同的公司/客户机在其中连接,但使用不同的数据库 例如:Node.js 一个带有nodejs的应用程序,每个客户端有不同的数据库,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我想用NodeJ创建一个应用程序,不同的公司/客户机在其中连接,但使用不同的数据库 例如: 在本地主机上运行的应用程序节点:3001 在本地主机上运行的Mongo服务器:27017 客户端(CLIENT1)访问nodejs应用程序并修改数据 在其数据库->localhost:27017/client1中 另一个客户端(CLIENT2)也会执行同样的操作并访问应用程序 nodej,但在localhost:27017/client2中修改其数据 对于每一个注册该应用程序的客户,也是如此 ----
- 在本地主机上运行的应用程序节点:3001
- 在本地主机上运行的Mongo服务器:27017
- 客户端(CLIENT1)访问nodejs应用程序并修改数据 在其数据库->localhost:27017/client1中
- 另一个客户端(CLIENT2)也会执行同样的操作并访问应用程序 nodej,但在localhost:27017/client2中修改其数据
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创建数据库
您要做的是创建一个多租户nodejs应用程序 您所采取的方法几乎没有缺点:
- 一个用户id有一个公共数据库,它将告诉要连接到哪个数据库,然后每个客户端有一个数据库。这意味着您有n+1个连接
- 您的应用程序将无法扩展,因为您将始终为数据库提供过多/不足的资源,或者更糟糕的是为每个新客户机部署更改
我也有同样的问题,为此写了一篇文章 您将如何通过名称/id识别不同的客户端?数据库模式对于不同的客户机是不同的还是相似的?模式是相似的,识别不同客户机的目的是通过一个id。例如,client1具有id 198,使用该id创建数据库。我已决定使用单个mongo数据库。我读了这篇文章,你使用sequelize,它必须改变很多已经实现的东西。因此,我将使用一个数据库,仔细考虑客户机的ID。谢谢你的回答,我认为它是有效的,因为它让我思考。