Search all documents in a collection using Mongoid

I was messing around with Mongo, but I can't get this simple example to work. I am just trying to get all the 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).

The database connection is well established, and the collection named categories contains several documents.

+6
source share
1 answer

Category really has no each method, because it is a model class, not a collection. However, it does have several methods that return objects similar to collections. One of them is all . Therefore, the code should look like this:

 Category.all.each do |test| puts test.inspect end 
+12
source

Source: https://habr.com/ru/post/918023/


All Articles