2

Trying to get Mongoid up and running with Sinatra on Heroku (MongoHQ). Previous experience with Rails but first time with the stack and Sinatra.

Started with one of the simple examples on the web (app.rb):

require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongoid'

configure do
  Mongoid.load!('mongoid.yml')

  Mongoid.configure do |config|
    if ENV['MONGOHQ_URL']
      conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
      uri = URI.parse(ENV['MONGOHQ_URL'])

      # problem happens here 
      config.master = conn.db(uri.path.gsub(/^\//, ''))
    else
      config.master = Mongo::Connection.from_uri("mongodb://localhost:27017").db('test')
    end
  end
end


# Models
class Counter
  include Mongoid::Document

  field :count, :type => Integer

  def self.increment
    c = first || new({:count => 0})
    c.inc(:count, 1)
    c.save
    c.count
  end
end

# Controllers
get '/' do
  "Hello visitor n" + Counter.increment.to_s
end

For reference, mongoid.yml looks like:

development:
  sessions:
    default:
      database: localhost
production:
  sessions:
    default:
      uri: <%= ENV['MONGOHQ_URL'] %>

As per app.rb (# problem happens here), my logs say:

/app/app.rb:15:in `block (2 levels) in <top (required)>': undefined method `master=' for Mongoid::Config:Module (NoMethodError)
    from /app/vendor/bundle/ruby/1.9.1/gems/mongoid-3.0.3/lib/mongoid.rb:112:in `configure'
from /app/app.rb:11:in `block in <top (required)>'
from /app/vendor/bundle/ruby/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:1273:in `configure'
from /app/app.rb:8:in `<top (required)>'

I have also tried variants, including:

config.master = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXX')
Mongoid.database = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXXXX')

But get the same error:

undefined method `master` for Mongoid::Config:Module (NoMethodError)

or:

undefined method `database=` for Mongoid::Config:Module (NoMethodError)

What am I missing?

2 Answers 2

3

Shouldn't be

configure do
  Mongoid.load!('mongoid.yml')
end

enough?

That's what the mongid docs are saying. The MONGOHQ_URL environment variable already contains every information to initialize the connection to the db.

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

1 Comment

Thanks @iltempo :) I figured out the problem, just writing up the answer.
3

So was using Mongoid 3.x ... which:

  • Doesn't use 10gen driver: uses Moped
  • Doesn't use config.master

The canonical sample code above which is all over the web works out of the box with Mongoid 2.x so have dropped back to that for the time being.

Thanks!

Comments

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.