Mongoid找到嵌入的文档

问题描述:

我试图通过它的id搜索嵌入的文档,并将其返回。这是可能的,但只有在我看来,通过使用mongo来查找嵌入它的文档,然后在ruby中搜索该文档以获取我之后的嵌入文档。就像这样:Mongoid找到嵌入的文档

# 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 

看似简单,但我没有发现任何东西我明明喜欢在谷歌/ SO搜索。

想法?

+2

请您提供您的模型? – 2013-03-18 18:18:10

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

现在我在嵌入式文档中包含以下功能。它要求您在嵌套关系上设置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 

我用这个要点上我的嵌入式文件覆盖find方法:https://gist.github.com/cblavier/7889042

,当我想用​​DelayedJob延迟嵌入文档的方法(因为DJ工人将使用查找(ID这是特别方便)进行反序列化这项工作)

+0

你是MVP的人!在多态嵌入的情况下仍然很难(在这种情况下,除了导出原始ID字符串/类型并使用适当的find_through方法外别无选择) – 2017-04-08 14:23:58

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