【问题标题】:Mongoid find embedded documentMongoid 查找嵌入文档
【发布时间】:2013-03-10 07:57:59
【问题描述】:

我正在尝试通过其 id 搜索嵌入文档,并将其返回。这是可能的,但据我所知,只有通过使用 mongo 查找嵌入它的文档,然后在 ruby​​ 中搜索该文档以查找我想要的嵌入文档。像这样:

# commenter.rb
  def post
    # todo: find syntax do avoid double query
    if user = User.any_of({'posts.commenter_ids' => self.id}).last
      user.posts.where('commenter_ids' => self.id).last
    end
  end

看起来很简单,但我在 google/SO 搜索中没有找到我喜欢的任何东西。

想法?

【问题讨论】:

  • 能否提供您的模型?

标签: ruby-on-rails mongodb mongoid


【解决方案1】:

我使用以下要点覆盖我的嵌入式文档上的 find 方法:https://gist.github.com/cblavier/7889042

当我想使用DelayedJob延迟嵌入文档方法时特别方便(因为DJ worker会使用find(id)来反序列化作业)

【讨论】:

  • 你是MVP!在多态嵌入的情况下仍然很难(在这种情况下,别无选择,只能导出原始 ID 字符串/类型并使用适当的 find_through 方法)
【解决方案2】:
class Order
  embeds_many Products
end

class Product
  embedded_in Order
end

prod_id = "1234" # the embedded doc's _id you request
o = Order.find(product_ids: prod_id)
p = o.products.find(prod_id)

另见Does querying Mongoid embedded documents hit the database server after loading a parent document

【讨论】:

    【解决方案3】:

    现在我正在嵌入的文档中包含以下功能。它要求您在嵌套关系上设置 inverse_of 选项。

    # Returns the parent "embedded_in" relationship for this document
    # @return [Mongoid::Relations::Metadata]
    def self.parent_relationship
      @parent_relationship ||= relations.values.find do |relation|
        relation.macro == :embedded_in
      end
    end
    
    # finds the document off of a root document. This method currently only works correctly if
    # you explicitly set the inverse_of value on the embedded_in relationship
    # @param [string | Moped::BSON::ObjectId] id
    def self.find_using_parent(id)
      id = id.is_a?(Moped::BSON::ObjectId) ? id : Moped::BSON::ObjectId(id)
      parent = parent_relationship.class_name.to_const.where("#{parent_relationship.inverse_of}._id" => id).first
      if parent
        parent.__send__(parent_relationship.inverse_of).find(id)
      end
    end
    

    【讨论】:

      【解决方案4】:

      如果没有嵌入的文档,您将无法找到资源。如果你只是想要两者之间的关系而不是嵌入它,你应该使用 has_many 而不是 embeds_many http://mongoid.org/en/mongoid/docs/relations.html#has_many。 然后,您可以找到没有相关文档的文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-19
        • 2011-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        相关资源
        最近更新 更多