层次结构的流星数据库设计

Meteor database design for hierarchical structure

我是 Meteor 和 Mongo 的新手,我有一些基本的数据库设计问题。

假设我正在制作类似 Advance Wars 的回合制策略游戏。我不确定如何构建我的数据。

我在 html:

中做了一个小演示
{{#each chars}}
  <div class='char' style={{get_style}}>
      ...
  </div>
{{/each}}

我在 Template.body:

上定义了这个助手
Template.body.helpers({
  chars: function() {
    return Characters.find({});
  },
  ...
})

当我一次只有一个游戏 运行 时,这很好用。但是当我同时玩多个游戏 运行 时,我不确定如何进行这项工作。

我猜一种方法是制作游戏合集。这些游戏中的每一个都引用了两个或更多玩家,每个玩家都可以有一个角色列表。每个角色都可以有一个 x 和 y 位置。但是我不确定我将用什么查询替换 Characters.find({})

我想可能是 Game.findOne({game_id: game_id}).players[player_id].characters。但我不确定那里的性能影响是什么。 Meteor 会在每次角色移动时拉下整个游戏对象吗?我不太明白 Meteor 到底在做什么。

我想另一种可能需要进行最小更改的可能性是执行类似 Characters.find({game_id: 123, player_id: 1}) 的操作。然后我会把所有游戏中的所有角色都放在一个大集合中。在游戏下没有角色 "encapsulated" 对我来说似乎有点奇怪,但也许这就是要走的路。

实际上,既然我已经写完了,似乎第二种选择更有意义。我想我会将所有其他内部游戏对象定义为单独的集合。这是解决此问题的好方法吗?

假设您的 collection 存储的物品看起来像

{
  _id: String,
  started: Date,
  players: [{
    _id: String,
    name: String,
    characters: [{
      _id: String,
      x: Number,
      y: Number
    }, {
      // ...
    }]
  }, {
    // ...
  }]
}

如果你有一个 _id 的游戏并且你需要获得所有玩家和他们的角色,你只需

let gameId = 'whatever';
const games = Games.find({
  _id: gameId
});

之后,在 games 中,您有一个游标,可以让您遍历单个元素,即您通过 ID 选择的游戏(在设计上是唯一的)。

然后,在您的模板中,您可以

<div class="games">
  {{#each games}}
    <h1>{{started}} — game's `started` scalar property.</h1>
    {{#each players}}
      <div class="player" id="{{_id}}">
        <h2 id="{{_id}}">{{name}} — player's name</h2>
        {{#each characters}}
          <h3 id="{{_id}}">{{x}}, {{y}} — coordinates of a character</h3>
        {{/each}}
      </div>
    {{/each}}
  {{/each}}
</div>

请注意 _id 如何尊重当前上下文。

另一种方法是使用 plain-object 代替游标,但只有在保证查询结果是单个元素的情况下才应使用它:

let gameId = 'whatever';
const game = Games.findOne({
  _id: gameId
});

模板看起来会有点不同。由于您只有一个 plain-object,因此您没有任何要迭代的内容。因此,您可以访问此 object 的属性,省略最顶层的上下文并将其替换为 with 块:

<div class="game">
  {{#with game}}
    <h1>{{started}} — game's `started` scalar property.</h1>
    {{#each players}}
      <div class="player" id="{{_id}}">
        <h2 id="{{_id}}">{{name}} — player's name</h2>
        {{#each characters}}
          <h3 id="{{_id}}">{{x}}, {{y}} — coordinates of a character</h3>
        {{/each}}
      </div>
    {{/each}}
  {{/with}}
</div>

请确保您的模板(或整个客户端)已订阅 Games collection,并且此 collection 已在服务器上发布且 returns 整个字段集并且不查询数据(或者它查询但你控制它)。