Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid Without Rails

I'm playing with a standalone ruby application and can't configure Mongoid 3.0.13 to work.

I've run across a couple example apps that have configuration blocks like:

Mongoid::Config.instance.from_hash({"database" => "oid"}) 

Or

Mongoid.configure do |config|
 name = "mongoid_test_db"
 host = "localhost"
 port = 27017
 config.database = Mongo::Connection.new.db(name)
end

These result in:

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

It seems the configuration settings have changed recently.

I also tried:

Mongoid::Config.connect_to("sweet")

But that seems to do nothing.

like image 687
Tyler DeWitt Avatar asked Mar 07 '13 23:03

Tyler DeWitt


2 Answers

By "standalone" I'm assuming you mean not rails. Mongoid actually provides an easy way to make this work regardless of how you're running it.

  1. Define a mongoid.yml file with your database connection info in it like normal.
development:
  clients:
    default:
      database: mongoid
      hosts:
        - localhost:27017
  1. Make sure you've required Mongoid in your application.
  2. Call Mongoid.load! to have Mongoid parse your configuration file and initialize itself.
require 'mongoid'
Mongoid.load!('/path/to/your/mongoid.yml')

This info can also be found here under the "Sinatra, Padrino, and others" section: http://mongoid.org/en/mongoid/docs/installation.html

The same approach is applicable for non-webapps. Hope that helps.

like image 78
Brandon Black Avatar answered Oct 30 '22 04:10

Brandon Black


Try this:

prompt> ruby myapp.rb 
hello world

prompt> cat mongoid.yml 
development:
  sessions:
    default:
      database: myapp
      hosts:
        - localhost:27017

prompt> cat myapp.rb 
require 'mongoid'
Mongoid.load!("mongoid.yml", :development)
puts "hello world"
like image 29
neoneye Avatar answered Oct 30 '22 04:10

neoneye