1

I am trying to make a multi-tenant application in MEAN, based on value of some variable it should pick a mongoDB Connection form pool of connections and do CURD Operations on a collection.

var mongoose    = require('mongoose');
var connectionPool = {};

connectionPool['dbName1'] =  mongoose.createConnection('mongodb://localhost/database1');

connectionPool['dbName2'] =  mongoose.createConnection('mongodb://localhost/database2');

connectionPool['dbName3'] = mongoose.createConnection('mongodb://localhost/database3');

The issue is connection object when used to do CURD operation is not working.

Error - db.collection(...).find(...).exec is not a function

Thanks.

utkarsh sharma
  • 149
  • 2
  • 12

1 Answers1

1

You are mixing mongodb API with mongoose's.

Since you are working with mongoose, you can create models attached to a certain connection:

https://stackoverflow.com/a/19475270/2013580

var conn      = mongoose.createConnection('mongodb://localhost/testA');
var conn2     = mongoose.createConnection('mongodb://localhost/testB');

// stored in 'testA' database
var ModelA    = conn.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testA database' }
}));

// stored in 'testB' database
var ModelB    = conn2.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testB database' }
}));
Community
  • 1
  • 1
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • I was trying to add a tenant dynamically, is there a way to do that? – utkarsh sharma Feb 05 '17 at 15:03
  • @utkarshsharma you can do all that dynamically. Just set the models definition in every connection, build a function that does that based on a connection parameter. – zurfyx Feb 05 '17 at 15:43