Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created March 16, 2012 20:19
Show Gist options
  • Save aheckmann/2052385 to your computer and use it in GitHub Desktop.
Save aheckmann/2052385 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
mongoose.connect('localhost', 'testing_multiTenant');
/**
* User schema.
*/
var UserSchema = new mongoose.Schema({
name: String
, prefix: { type: String, required: true }
});
/**
* Instance method.
*
* Returns models (prefixed collections) for the user.
*/
UserSchema.methods.getModel = function (name) {
return this.model(this.prefix + name);
}
/**
* Create the default Model.
* no prefix
*/
var User = mongoose.model('User', UserSchema);
/**
* Blog post schema.
*/
var PostSchema = new mongoose.Schema({
title: String
, date: { type: Date, default: Date.now }
, _author: { type: mongoose.Schema.ObjectId }
});
var PostSchemaName = 'Posts'
/**
* Generates uniquely prefixed models/collections for a user.
*/
function createTenancy (user, cb) {
user.prefix = 'blah'+String(Math.random()).substring(2,6);
user.save(function (err) {
if (err) return cb(err);
mongoose.model(user.prefix + PostSchemaName, PostSchema);
cb();
});
}
mongoose.connection.on('open', function () {
// create a user
var kermit = new User({ name: 'Kermit' });
// set up prefixes
createTenancy(kermit, function (err) {
if (err) return console.error(err.stack);
// get all models through getModel() instance method
var P = kermit.getModel('Posts');
var post = new P({ _author: kermit, body: 'green' });
console.error('saving kermits post to collection %s', P.modelName);
post.save(function (err) {
if (err) return console.error(err.stack);
P.findById(post, function (err, post) {
if (err) return console.error(err.stack);
console.error('found prefixed post', post);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
});
});
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment