Mongoid找到嵌入式文件

我正在尝试通过其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搜索中找到任何我喜欢的东西。

思考?

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

当我想使用DelayedJob延迟嵌入式文档方法时,这是特别方便的(因为DJ工作者将使用find(id)来反序列化作业)

 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) 

另请参阅加载父文档后查询Mongoid嵌入文档是否到达数据库服务器

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

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