Using Mongoid on Heroku with MongoHQ

If you are using Rails 3 and you want to use mongohq with heroku along with the mongoid gem then after you install mongohq on your heroku instance you will need to open or create preninitializer.rb  file and do the following.

require ‘uri’

  mongo_uri = URI.parse(ENV[“MONGOHQ_URL”])
  ENV[‘MONGOID_PORT’] = mongo_uri.port.to_s
  ENV[“MONGOID_USERNAME”] = mongo_uri.user
  ENV[‘MONGOID_PASSWORD’] = mongo_uri.password
  ENV[‘MONGOID_DATABASE’] = mongo_uri.path.gsub(“/”, “”)

These environment variables should get picked up in the mongoid.yml file and configure everything to work correctly. Also make sure you add the uri: argument under production.

  uri: <%= ENV[‘MONGOHQ_URL’] %> 
  host: <%= ENV[‘MONGOID_HOST’] %>
  port: <%= ENV[‘MONGOID_PORT’] %>
  username: <%= ENV[‘MONGOID_USERNAME’] %>
  password: <%= ENV[‘MONGOID_PASSWORD’] %>
  database: <%= ENV[‘MONGOID_DATABASE’] %>