8

I have a multi-domain Rails 4 app where the request.domain of the http request determines which functionality I expose a given visitor to.

Each domain in my app should be served by its own MongoDB database. E.g. domain1.com is served by db_for_domain_1, etc.

I can read in the MongoDB docs on runtime persistence that

Mongoid.override_database("db_for_#{request.domain}")

enables me to switch database on the fly.

But how do I keep the persistence when I bypass Mongoid and use the mongo Shell method db.collection.insert()? I will still do it from within my application though.

The answer might be in the MongoDB docs on collection access, but I don't understand it. So how do I switch database before/during this operation?:

MyModel.collection.insert({field_1: "Value 1", field_2: "Value 2"})
Cjoerg
  • 1,271
  • 3
  • 21
  • 63
  • Do you use the same model across the databases? – tegon Oct 22 '15 at 12:05
  • Yep, I do! I us the exact same models. – Cjoerg Oct 22 '15 at 12:18
  • On "...how do I keep the persistence...": An ODM cannot know about operations made outside of that framework. When you insert the doc through the mongo shell command, trigger a read on that doc through Mongoid to load it into the persistence layer. – Steve Tarver Oct 24 '15 at 18:52

1 Answers1

4

If I understand your question correctly: you have an app that connects to different mongodbs on different servers, but want to use mongo shell to connect to the database outside of your application? If true, you would connect to the desired database through the shell with

mongo db_for_domain_1:<port>/<dbName>

and then

db.<collectionName>.insert({doc})

see mongo --help for username and password options.

Steve Tarver
  • 3,030
  • 2
  • 25
  • 33
  • Thanks @SteveTarver. I'm very glad that it is possible to switch the database. I'm not quite sure though how to interpret this line: `mongo db_for_domain_1:/`. Is `mongo` the Ruby method, and `db_for_domain_1:/` a key,value argument? In that case I understand the value part of the argument (could e.g. be the port `27017`), but I don't understand the key part of the argument. – Cjoerg Oct 20 '15 at 06:40
  • Oh sorry, no I want to connect from within my application. The only thing I want to circumvent is Mongoid (because I am using a mongo Shell method). So I need something that works e.g. from a controller. – Cjoerg Oct 20 '15 at 06:49
  • Sorry, no rails or Mongoid experience, can't offer help there. Good luck though, sounds like an interesting challenge. – Steve Tarver Oct 20 '15 at 07:45