【问题标题】:limiting fields returned from a mongoid polymorphic relation限制从 mongoid 多态关系返回的字段
【发布时间】:2012-03-20 04:31:34
【问题描述】:

我在 mongoid 中有一个多态关系,如下所示:

class Company
  include Mongoid::Document
  field :name, :type => String
  has_many :posts, as: :postable
end

class Person
  include Mongoid::Document
  field :name, :type => String
  has_many :posts, as: :postable
end

class Post
  include Mongoid::Document
  belongs_to :postable, polymorphic: true
end

我希望有时(而不是大多数时候)只加载 postable 的某些字段。在非多态关系中(比如只有一个人有帖子)我可以这样做:

Person.only(:name).find(some_post.postable_id)

但这在多态关系中是否可能?

【问题讨论】:

  • 你能说出你想要什么文件或查询吗?

标签: mongoid


【解决方案1】:

我可以看到几种方法,但我不确定哪种方法最好。复杂的关系不是 MongoDB 的强项,如果您开始扫描多个文档以获取答案,其他 NoSQL 和查询可能会变得昂贵。

在哪里使用:

Person.where(name: "name").posts.where(postable_id: "id")

从帖子中找到父母:

Post.where(id: "id").person.only(:name)

(注意postable_id和id不是同一个值!)

但是,要小心。如果您所做的只是列出帖子,那么您最好在帖子中包含此人的姓名,并在他们更改姓名时编写回调以更新此人的姓名。或者,如果您从一个人链接到 cmets,为什么不在 Person 模型中包含评论 ID(或足够的数据来建立链接),这样您就可以通过一个文档调用获取所有 cmets。同样,如果您要获得计数,请使用回调来计算 Person 模型中的帖子计数,这样您就不会每次都映射数百个帖子。

我希望这会有所帮助,如果没有提供更多信息,我会更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多