如何在Mongoid中引用嵌入式文档? [英] How to reference an embedded document in Mongoid?

查看:78
本文介绍了如何在Mongoid中引用嵌入式文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Mongoid,假设我有以下课程:

Using Mongoid, let's say I have the following classes:

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

如您所见,我正在尝试对一个简单的游戏世界环境进行建模,在该环境中地图嵌入位置,并且玩家将单个位置作为其当前位置.

As you can see, I'm trying to model a simple game world environment where a map embeds locations, and a player references a single location as their current spot.

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

Using this approach, I'm getting the following error when I try to reference the "location" attribute of the Player class:

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

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

My understanding is that this is because the Location document is embedded making it difficult to reference outside the scope of its embedding document (the Map). This makes sense, but how do I model a direct reference to an embedded document?

推荐答案

由于地图是它们自己的集合,因此您需要遍历每个Map集合,在其中搜索播放器所引用的位置.

Because Maps are their own collection, you would need to iterate over every Map collection searching within for the Location your Player is referenced.

您不能直接访问嵌入的文档.您必须进入整个收藏集并逐步解决问题.

You can't access embedded documents directly. You have to enter through the collection and work your way down.

为避免迭代所有地图,您可以在播放器"文档中存储位置"引用和地图"引用.这使您可以链接选择地图的条件,然后选择其中的位置.您必须在Player类上编写一个方法来处理此问题.

To avoid iterating all of the Maps you can store both the Location reference AND the Map reference in your Player document. This allows you to chain criteria that selects your Map and then the Location within it. You have to code a method on your Player class to handle this.

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

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

So, similar to how you answered yourself except you could still store the location_id in your player document instead of using the coord attribs.

另一种方法是将地图",位置"和播放器"放入自己的集合中,而不是将位置"嵌入到您的地图"集合中.然后,您可以使用引用关系而无需做任何花哨的工作……但是,您实际上只是在使用分层数据库,就像现在是关系数据库一样.

Another way would be to put Maps, Locations, and Players in their own collections instead of embedding the Location in your Map collection. Then you could use reference relationships without doing anything fancy... however your really just using a hierarchical database likes it's a relational database at this point...

这篇关于如何在Mongoid中引用嵌入式文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆