使用 Mongoid:可以同时在多个文档中使用 embed_in 吗?

Using Mongoid: Can you use embed_in in multiple documents at the same time?

我正在习惯使用 Mongoid,但是我 运行 在尝试使用 Mongoid 的情况下遇到了这个问题。

我有一个游戏,游戏有队伍,队伍有选手,游戏有相同的选手。

class Game
  include Mongoid::Document

  embeds_many :Players
  embeds_many :Teams
end

class Team
  include Mongoid::Document

  embedded_in :Game
  embeds_many :Players
end

class Player
  include Mongoid::Document

  embedded_in :Game
  embedded_in :Team
end

现在当我运行这段代码使用

game = Game.new( :id => "1" )

game.save

player = Player.new()
game.Players << player

team = Team.new()
game.Teams << team
team.Players << player

我希望有一个游戏,有一个团队,那个团队有一个玩家,并且那个玩家也在游戏中。

那我运行

newgame = Game.find("1")
newteam = newgame.Teams.first
newplayer = newgame.Players.first
newplayer2 = newteam.Players.first

newplayer存在,newplayer2不存在。

这是怎么回事?

我只能在一个对象中嵌入一个文档吗,有什么办法吗?我尝试将其中一个关系设置为 belong_to,如果根据输出嵌入文档,则不允许这样做。

我知道我可以更改模型(游戏不需要 link 给玩家)我只是想知道这种关系是否违反了某些规则,或者是否有一些技巧可以使它正常工作声明。

作为附带问题,有人可以在这种情况下复习一下 "saving" 的规则吗(或者假设玩家没有融入团队)。设置好后,我似乎不必保存游戏、团队和玩家来记录嵌入。如果我保存其中任何一个,其他的就会自动保存。还是在建立关系后修改文档时是否必须保存每个单独的文档(假设修改也是在建立关系后完成的)。

您不想使用 embeds_many。将 "embeds" 文档放入父文档,然后将其嵌入多个父文档就没有意义了,因为那样您的 Player 数据将在多个位置重复。

想想当数据存储在多个位置时持续更新和保持数据的一致性将是一场多么可怕的噩梦。

您想要使用的是 has_many 来模拟这些关系。这仅将文档的 _id 存储在父级中,而实际文档存储在单独的集合中,并允许多个父级引用它。

http://mongoid.org/en/mongoid/docs/relations.html#has_many

One to many relationships where the children are stored in a separate collection from the parent document are defined using Mongoid's has_many and belongs_to macros.

class Game
  include Mongoid::Document

  has_many :Players
  has_many :Teams
end

class Team
  include Mongoid::Document

  belongs_to :Game
  has_many :Players
end

class Player
  include Mongoid::Document

  belongs_to :Game
  belongs_to :Team
end