1

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

想法?

4

4 回答 4

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)

另请参阅在加载父文档后查询 Mongoid 嵌入文档是否会命中数据库服务器

于 2013-12-19T18:17:21.087 回答
2

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

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

于 2013-12-10T15:23:43.770 回答
1

现在,我将以下功能包含到我的嵌入式文档中。它要求您在嵌套关系上设置 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
于 2013-08-13T20:36:04.940 回答
-1

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

于 2013-03-10T15:32:53.650 回答