Alex Rivera | Logout

Finding all documents in a collection with Mongoid

Asked 2012-06-13T19:29:26.483
10

I have been fiddling with Mongo, but can't get this simple example to work. I'm simply trying to retrieve all documents in a collection:

require 'mongoid'

# configuration ...    

class Category

  include Mongoid::Document
  field :name, type: String

end

Category.each do |test|
  puts test.inspect
end

I get the error: undefined method 'each' for Category:Class (NoMethodError).

Connection to the database is well established, and a collection named categories contains a few documents.

Edit
Report

1 Answer

14

Category indeed doesn't have a method each because it's a model class, not a collection. It has, however, several methods that do return collection-like objects. One of them is all. So the code should look like this:

Category.all.each do |test|
  puts test.inspect
end
answered 2012-06-13T19:44:58.357

Your Answer