使用 Mongoid 获取实际结果数组
通过 Rails 中的常规 ActiveRecord/SQL 设置,当我在控制台中执行命令 *.where
、*.all
等时,我会返回实际的记录项数组。然而,在切换到 Mongoid 后,我反而得到了一个标准。我如何获得实际结果?
这就是我现在得到的...
ruby-1.9.2-p180 :001 > App.all
=> #<Mongoid::Criteria
selector: {},
options: {},
class: App,
embedded: false>
With a regular ActiveRecord/SQL setup in Rails, in console when I execute commands *.where
, *.all
etc., I get back the actual array of record items. However, after switching to Mongoid, I instead get back a criteria. How do I get the actual results?
This is what I get now...
ruby-1.9.2-p180 :001 > App.all
=> #<Mongoid::Criteria
selector: {},
options: {},
class: App,
embedded: false>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在 Mongoid 中查询模型时,它会返回一个条件对象(如您所述),在您从条件请求数据之前,它实际上不会运行查询。
您需要做的就是使用
each
或map
或任何数组方法迭代结果,如下所示:或者,如果您只需要数组,您可以只需根据条件调用
to_a
即可:When you query a model in Mongoid, it returns a criteria object (as you've stated), it doesn't actually run the query until you request data from the criteria.
All you need to do is iterate over the results, using
each
ormap
or any of the array methods, like this:Alternatively, if you just want the array, you can just call
to_a
on the criteria:App.all.entries
也可以工作。App.all.entries
works as well.