Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all documents in a collection with Mongoid

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.

like image 941
user2398029 Avatar asked Jun 13 '12 19:06

user2398029


1 Answers

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
like image 90
Sergio Tulentsev Avatar answered Oct 08 '22 05:10

Sergio Tulentsev