0

如何在推送过程中为Firebase的每个条目添加uniqueId?现在我的代码如下所示:向Firebase添加唯一ID

 this.games.push({ 
         game_name: data.gameName, 
         number_of_players: data.number_of_players, 
         random_id: this.randomId, 
         admin: data.admin, 
         first_name: data.your_name, 
         player_array: [this.combinePlayerName(this.firstName, this.admin)] 
        }) 

我使用AngularFire2,并抢得一个数据库参考this.games:

constructor(public navCtrl: NavController, public alertCtrl: AlertController, af: AngularFire) { 
    this.games = af.database.list('/games'); 
    this.ids = af.database.list('/games/random_id'); 
} 

如何推到DB和,而不是得到一个列表看起来是这个随机生成的ID的:

enter image description here

我得到故意标识的,我有知识,能在客户端代码中选择的列表?

+0

你是什么意思“有知识”?在推送之前或之后有没有特别想要处理的ID?无论如何,推送ID并非完全随机,它们的初始组件是时间戳:https://gist.github.com/mikelehen/3596a30bd69384624c11 – cartant

+0

o真的吗?是的措辞有点混乱,我想给他们Id像:331,123或554,而不是:KbaZqVQBp580Zzt4Uty和该列表中的其他人 –

+0

您可以使用['set'](https:// firebase .google.com/docs/reference/js/firebase.database.Reference#set)或['update'](https://firebase.google.com/docs/reference/js/firebase.database.Reference#update)用任何你喜欢的ID作为钥匙,但你的责任在于确保钥匙是唯一的。通常,出于这个原因鼓励使用推送。 – cartant

回答

1

有几种方法可以做到这一点:

获得推ID并将其存储在另一个节点:

有一种方式来获得在AngularFire推法目前推ID 。因此,您可以将“随机生成的ID”更改为您“知道的”ID。

this.games.push({ 
    game_name: data.gameName, 
    number_of_players: data.number_of_players, 
    random_id: this.randomId, 
    admin: data.admin, 
    first_name: data.your_name, 
    player_array: [this.combinePlayerName(this.firstName, this.admin)] 
}).then((game) => { 
    this.ids.push(game.key); 
}) 

除此之外,你其实可以使用set方法,而不是推的更改推动关键:

this.af.database.object("games/"+this.randomId).set({ 
     game_name: data.gameName, 
     number_of_players: data.number_of_players, 
     random_id: this.randomId, 
     admin: data.admin, 
     first_name: data.your_name, 
     player_array: [this.combinePlayerName(this.firstName, this.admin)] 
    }) 

凡AF包含注入AngularFire模块

constructor(public af : AngularFire) { } 

即使此方法正常工作,它也会为您提供另一项创建唯一ID的任务,这是Firebase可以从第一种方法为您执行的任务。

此外,正如上述评论中所述,您可以使用random_id子节点来查询您的列表。