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"})
3
  • Do you use the same model across the databases? Commented Oct 22, 2015 at 12:05
  • Yep, I do! I us the exact same models. Commented Oct 22, 2015 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. Commented Oct 24, 2015 at 18:52

1 Answer 1

4
+25

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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:<port>/<dbName>. Is mongo the Ruby method, and db_for_domain_1:<port>/<dbName> 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.
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.
Sorry, no rails or Mongoid experience, can't offer help there. Good luck though, sounds like an interesting challenge.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.