Skip to content

Instantly share code, notes, and snippets.

@alancasagrande
Last active May 7, 2021 12:04
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alancasagrande/23e6284e24dadafce8c0 to your computer and use it in GitHub Desktop.
Save alancasagrande/23e6284e24dadafce8c0 to your computer and use it in GitHub Desktop.
Multi-tenant app example with multiple databases. It will create 40 databases, use this gist to the delete them afterwards: https://gist.github.com/alancasagrande/4aa8b4a45ff7c8829ff5
var express = require('express');
var mongoose = require('mongoose');
var dbs = {};
for (var i = 0; i < 40; i++) {
dbs['t' + i] = mongoose.createConnection('mongodb://localhost/t' + i + '__multitenant', { server: { poolSize: 5 } });
}
var app = express();
app.use(express.bodyParser());
app.post('/posts', function (req, res) {
Author(req.query.tenant).findOne().exec().then(function (author) {
req.body.author = author.id;
Post(req.query.tenant).create(req.body).then(function (post) {
res.json(post);
}, function (err) {
console.log('Post error');
res.send(500, err);
});
});
});
app.get('/posts', function (req, res) {
Post(req.query.tenant).count().exec().then(function (count) {
res.send({ count: count });
});
});
app.listen(3000);
console.log('Listening...');
var authorSchema = mongoose.Schema({
name: String
});
Author = function (prefix) {
return dbs[prefix].model('Author', authorSchema);
};
var postSchema = mongoose.Schema({
name: String,
date: { type: Date, default: Date.now },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author', $tenant: true },
});
Post = function (prefix) {
return dbs[prefix].model('Post', postSchema);
};
// insert tenants
for (var i = 0; i < 40; i++) {
Author('t' + i).create({ name: 'Author ' + i });
}
@bastianwegge
Copy link

bastianwegge commented May 11, 2018

Hey @alancasagrande, thank you very much for putting this code online!

Just wanted to point out that you're opening 200 Connections on your Database, are you aware of that? Since Version 3.8, mongoose offers a function called "useDb()" to avoid this ( see here https://github.com/Automattic/mongoose/wiki/3.8-Release-Notes#connection-pool-sharing ).

Cheers

@bikeshrestha
Copy link

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment