One app with nodejs, different datababase per client

Viewed 497

I want to create an application with nodejs in which different companies/clients connect but use different databases.

For example:

  • 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

And so on for every customer who signs up for the application.

--------EDIT----------

I've been testing things to get what I wanted and I think I've come up with a possible solution. The solution would be to create a connection to each database access. And when you have finished that access disconnect. I do not know if it is a good solution but I think it can be worth:

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")
        });
    }
}

when i launch requests:

localhost:3000/createdb?id=12

localhost:3000/createdb?id=13

localhost:3000/createdb?id=14

On the database server the databases are created with those id's

enter image description here

1 Answers
Related