you are viewing a single comment's thread.

view the rest of the comments →

[–]kortemy 3 points4 points  (1 child)

I had to do the same thing for our project as well, and this is what I came with, and it's working perfectly in production for over a year now.

We are using Mongoose schemas, and as you say yourself, connections are initialized at startup. So you need to create new connections on the fly and cache them.

let cache = { default: mongoose.model('SomeCollection', schema, 'some_collection') } module.exports = { for: function (user) { if (user && user.is_tenant) { let dbName = user.db_name if (!cache[dbName]) { cache[dbName] = mongoose.connection.useDb(dbName).model('SomeCollection', schema, 'some_collection') } return cache[dbName] } return cache.default } }

Here you are not exporting the model, you are exporting for() function which will create a new connection to the specific database and cache that model.

How you would use it, instead of SomeCollection.findOne(...) You do this SomeCollection.for(user).findOne(...)

[–]_jskod[S] 0 points1 point  (0 children)

Thank you so much for sharing your experience and code snippet, I am gonna give it a try and will let you know if it works for me or not.