Every time I need to get something from MongoDB I’m connecting to it. Is there a way I can connect only once (like a global variable) and use that variable in all the finds and actions?
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You have pretty much nailed this yourself. My preferred way to do this is to use a method in an initializer or class in the lib directory that initializes a class variable when it is not already set.
The following assumes you are using the standard Ruby driver. I’ve stuck it in a module, but you don’t really need to do this. I’m also selecting the database I wish to use, as I tend to use one per app.
Now in your controllers/models etc you can call the
mongodb_connectionmethod and work with that.