我一直在摆弄 Mongo,但无法让这个简单的示例发挥作用。我只是想检索集合中的所有文档:
require 'mongoid'
# configuration ...
class Category
include Mongoid::Document
field :name, type: String
end
Category.each do |test|
puts test.inspect
end
我收到错误:未定义方法 'each' for Category:Class (NoMethodError)。
与数据库的连接建立良好,名为 categories
的集合包含一些文档。
最佳答案
Category
确实没有方法 each
因为它是一个模型类,而不是一个集合。但是,它有几个方法可以返回类集合对象。其中之一是all
。所以代码应该是这样的:
Category.all.each do |test|
puts test.inspect
end
关于ruby - 使用 Mongoid 查找集合中的所有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11022010/