Last active
May 7, 2021 12:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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