2016-06-24 92 views
0

我有documentsgames集合。每个文档负责保存运行游戏所需的数据。这是我的文档结构返回数组元素的特定属性 - MongoDB /流星

{ 
    _id: 'xxx', 
    players: [ 
      user:{} // Meteor.users object 
      hand:[] //array 
      scores:[] 
      calls:[] 
     ], 
    table:[], 
    status: 'some string' 


} 

基本上这是我的纸牌游戏(电话桥)的结构。现在我想要发布的是,玩家将在他的浏览器(minimongo)中有他的hand数据以及其他玩家user, scores, calls字段。所以下载到浏览器的订阅将是这样的。

{ 
    _id: 'xxx', 
    players: [ 
      { 
       user:{} // Meteor.users object 
       hand:[] //array 
       scores:[] 
       calls:[] 
      }, 
      { 
       user:{} // Meteor.users object 
       scores:[] 
       calls:[] 
      }, 
      // 2 more player's data, similar to 2nd player's data 

     ], 
    table:[], 
    status: 'some string' 


} 

players.user对象具有_id属性,该属性区分用户。在流星发布方法中,我们可以访问this.userId,它返回正在请求数据的userId。这意味着我想要_idthis.userId匹配的那个用户的嵌套hand数组。我希望这些解释能帮助你写出更准确的解决方案。

回答

0

要从一个数组元素中获得一个特定的属性,你可以写下如下所示的代码db.games.aggregate([{$ unwind:“$ players”},{$ project:{“players.scores”: 1}}]);这给我们只有身份证和分数字段

+0

我不认为聚合会适用于我的情况。我需要返回一个查找光标流星发布 –

1

你需要做的是“规范化”你的收藏。您可以做的是创建一个单独的集合来保存这些数据,并将用户_id用作“Key”,然后仅在玩家字段中引用用户_id 。例如。

创建GameStats集合(或任何你想要的名称)

{ 
_id: '2wiowew', 
userId: 1, 
hand:[], 
scores:[], 
calls:[], 
} 

然后游戏集合

{ 
    _id: 'xxx', 
    players: [userId], 
    table:[], 
    status: 'some string' 


} 

所以,如果你想获得当前用户的内容请求数据

GameStats.find({userId: this.userId}).hand 

编辑

他们鼓励在某些情况下反规范化,但在上面发布的代码中,array不起作用。这里是一个来自mongoDB文档的例子。

{ 
_id: ObjectId("5099803df3f4948bd2f98391"), 
name: { first: "Alan", last: "Turing" }, 
birth: new Date('Jun 23, 1912'), 
death: new Date('Jun 07, 1954'), 
contribs: [ "Turing machine", "Turing test", "Turingery" ], 
views : NumberLong(1250000) 
} 
+0

感谢您的建议。由于MongoDB鼓励非规范化,我正在寻找比我的结构匹配的答案。 :) –