【发布时间】: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,将使用该名称创建数据库