22

使用 Mongoid,假设我有以下类:

class Map
  include Mongoid::Document

  embeds_many :locations
end

class Location
  include Mongoid::Document

  field :x_coord, :type => Integer
  field :y_coord, :type => Integer

  embedded_in      :map, :inverse_of => :locations
end


class Player
  include Mongoid::Document

  references_one   :location
end

如您所见,我正在尝试对一个简单的游戏世界环境进行建模,其中地图嵌入了位置,玩家将单个位置引用为他们的当前位置。

使用这种方法,当我尝试引用 Player 类的“位置”属性时出现以下错误:

Mongoid::Errors::DocumentNotFound: Document not found for class Location with id(s) xxxxxxxxxxxxxxxxxxx.

我的理解是,这是因为位置文档是嵌入的,因此很难在其嵌入文档(地图)的范围之外进行引用。这是有道理的,但是我如何对嵌入文档的直接引用进行建模呢?

4

5 回答 5

17

因为地图是它们自己的集合,所以您需要遍历每个地图集合,在其中搜索您的播放器被引用的位置。

您不能直接访问嵌入式文档。您必须通过收藏进入并向下工作。

为避免迭代所有地图,您可以在 Player 文档中存储位置参考和地图参考。这允许您链接选择您的地图的标准,然后选择其中的位置。您必须在 Player 类上编写一个方法来处理这个问题。

def location
  self.map.locations.find(self.location_id)
end

因此,类似于您自己回答的方式,只是您仍然可以将 location_id 存储在播放器文档中,而不是使用坐标属性。

另一种方法是将地图、位置和玩家放在他们自己的集合中,而不是将位置嵌入到您的地图集合中。然后你可以使用引用关系而不做任何花哨的事情......但是你真的只是使用分层数据库,就像它在这一点上是一个关系数据库......

于 2010-11-13T16:18:56.243 回答
11

请为 MongoDB 问题跟踪器上的“虚拟集合”功能投票:

http://jira.mongodb.org/browse/SERVER-142

这是第二个最受要求的功能,但仍未计划发布。也许如果有足够多的人投票支持它并将其排在第一位,MongoDB 团队最终会实施它。

于 2010-12-31T09:24:45.707 回答
6

在我的用例中,外部对象不需要引用嵌入的文档。从 mongoid 用户组中,我找到了解决方案:在嵌入式文档上使用 referenced_in,在外部文档上使用 NO reference。

class Page
  include Mongoid::Document
  field :title

  embeds_many :page_objects
end

class PageObject
  include Mongoid::Document
  field :type

  embedded_in       :page,    :inverse_of => :page_objects
  referenced_in     :sprite
end

class Sprite
  include Mongoid::Document
  field :path, :default => "/images/something.png"
end

header_sprite = Sprite.create(:path => "/images/header.png")
picture_sprte = Sprite.create(:path => "/images/picture.png")

p = Page.create(:title => "Home")
p.page_objects.create(:type => "header", :sprite => header_sprite)
p.page_objects.first.sprite == header_sprite
于 2011-03-05T17:32:19.040 回答
0

我目前的解决方法是执行以下操作:

class Map
  include Mongoid::Document

  embeds_many     :locations
  references_many :players, :inverse_of => :map
end

class Player
  referenced_in :map
  field :x_coord
  field :y_coord

  def location=(loc)
    loc.map.users << self
    self.x_coord = loc.x_coord
    self.y_coord = loc.y_coord
    self.save!
  end

  def location
    self.map.locations.where(:x_coord => self.x_coord).and(:y_coord => self.y_coord).first
  end  
end

这行得通,但感觉像一个kluge。

于 2010-10-08T13:31:09.423 回答
0

跳出框框思考,您可以将 Location 设为自己的文档,并使用 Mongoid Alize 从您的 Location 文档中自动生成 Map 文档中的嵌入数据。

https://github.com/dzello/mongoid_alize

这种方法的优点是在条件合适时可以获得高效的查询,而在没有其他方法的情况下可以对原始文档进行较慢的基于引用的查询。

于 2013-04-17T08:39:36.987 回答