Angular / Firestore-根据特定值创建多个文档

时间:2018-08-01 12:10:52

标签: angular google-cloud-firestore angularfire2

我有一个输入,用户可以在其中定义“游戏计数”和“玩家名称”。

如果用户输入“ 10”作为游戏计数,是否可能在添加新用户时创建了一个名为“ game_scores”的子集合,其中为10个得分中的每一个都添加了10个文档? >

在Firestore中,结构最终将是:

玩家(在此处添加了玩家名称)> Game_Scores> 10个文档(每个文档的值为'game_score:0')

或者,在玩家集合上为10个分数创建一个Array节点会更容易/更有效吗?

以下功能可将用户罚款添加到用户集合。我只是不确定如何创建具有一定数量文档的子集合。

addUser(userName){
  const newUser: any = {
    userName: userName,
  };

  this.usersCollection.add(newUser).then((docRef) => {
    const gameID = docRef.id;
  });
}

1 个答案:

答案 0 :(得分:1)

是的,您可以这样做。可以说您有这个对象:

const games = [
 {
  game_score: 0,
  ..
  ..
 },
 {
  game_score: 0,
  ..
  ..
 },
 {
  game_score: 0,
  ..
  ..
 },
]

我添加了更多字段,因为您可能想在某个时间(时间戳或有关游戏的任何其他信息)进行操作。

因此您可以迭代此数组,然后:

games.forEach(game => {
 this.usersCollection.doc(`${userID}`).collection<any>('games').add(game);
})

就这么简单,您可以创建新的嵌套集合。

对于在新集合或对象中执行此操作是否更好的问题:
我认为最好在新集合中进行操作,因为您将来可能希望添加身份验证和安全规则,并防止其他玩家访问每个用户的唯一字段,因此您可以将游戏限制为公开数据,并防止其他用户使用该用户的私有数据。


编辑:

如果您没有注释中所说的对象,那么您就可以拥有一些有价值的游戏,您可以执行以下操作:
在您的代码中:

setGameCount = (gameCount) => {
 const gCount = +gameCount; // <-- since you pass the value from the input, we convert it to number from string.
 const userID = 'yourUserID'; // <-- which user you are initialize
 for(let i=0 ; i< gCount; i++){
    const game = {
     game_score: 0,
    }
    this.usersCollection.doc(`${userID}`).collection<any>('games').add(game);
 }
}