Mongoid:如何仅加载通过引用延迟加载的对象的某些字段? [英] Mongoid: How to load only some fields of an object you lazy load via reference?
问题描述
出于性能方面的考虑,在编写蒙古式查询时,我会尽可能多地使用only()
关键字,以指定要加载的字段.
For performance reason, I use as often as possible the only()
keyword when writing up a mongoid query in order to specify the fields I want to load.
通常的怀疑是,例如当我只希望用户的所有管理员电子邮件仅用于显示时.
The usual suspect, is for instance when I want a user's email of all my admins only for display purposes.
我会写:
User.where(:groups => :admins).only(:email).each do |u|
puts u.email
end
之所以这样做,是因为我的用户模型中充满了很多数据,当我列出一堆电子邮件时,我很乐意忽略这些数据.
I do this because my user model are quite full of a lot of data that I can gladly ignore when listing a bunch of emails.
但是,现在让我们想象一下,我的用户是通过Project模型进行引用的,因此对于每个项目,我都可以这样做:project.user
.多亏了mongoid的延迟加载,当我调用引用时,我的对象用户才会被实例化(并从数据库中查询).
However, now let imagine, that my users are referenced via a Project model, so that for each project I can do: project.user
. Thanks to mongoid's lazy loading, my object user will only get instantiated (and queried from the DB) when I call upon the reference.
但是如果我想列出所有管理项目所有者的所有电子邮件怎么办?
But what if I want to list all the email of the owner of all admin project for instance ?
我会这样写:
Project.where(:admin_type => true).each do |p|
puts p.user.email
end
这里的主要问题是这样做,我为每个项目加载了整个用户对象,并且如果有很多与查询匹配的项目可能变得很繁琐.那么如何只加载电子邮件?
The major problem here is that doing this, I load the entire user object for each projects, and if there are lots of project matching the query that could get pretty heavy. So how do I load only the emails ?
我可以这样做:
User.where(:_id => p.user_id).only(:email).first.email
但是,这显然破坏了简单地执行简单语法的目的:
But this obviously defeat the purpose of the nice syntax of simply doing:
p.user.email
我希望我可以写类似的内容:p.user.only(:email).email
,但是我不能.有什么想法吗?
I wish I could write something like: p.user.only(:email).email
, but I can't. Any ideas ?
亚历克斯
推荐答案
Mongoid创建者的答案.还不可能它已作为功能请求添加.
Answer from creator of Mongoid. It's not possible yet. It's been added as feature request.
这篇关于Mongoid:如何仅加载通过引用延迟加载的对象的某些字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!