Skip to content

Instantly share code, notes, and snippets.

@alancasagrande
Last active June 9, 2024 21:02
Show Gist options
  • Select an option

  • Save alancasagrande/23e6284e24dadafce8c0 to your computer and use it in GitHub Desktop.

Select an option

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 });
}
@bikeshrestha
Copy link

thank you

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