【问题标题】:Add Unique Id to Firebase向 Firebase 添加唯一 ID
【发布时间】:2017-01-31 01:39:46
【问题描述】:

如何在推送时为 Firebase 的每个条目添加一个 uniqueId?现在我的代码看起来像:

      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');
}

我如何推送到数据库,而不是获得一个看起来像这样的列表,其中包含随机生成的 ID:

我得到一个我知道并且可以在客户端代码中选择的有意 Id 的列表?

【问题讨论】:

  • 你所说的“知道”是什么意思?在推送之前或之后,您有什么特别想对 ID 做的事情吗?无论如何,推送 ID 并不是完全随机的,它们的初始组件是时间戳:gist.github.com/mikelehen/3596a30bd69384624c11
  • 真的吗?是的,那里的措辞有点混乱,我想给他们的 ID 是:331、123 或 554,而不是:KbaZqVQBp580Zzt4Uty 和该列表中的其他人
  • 您可以使用setupdate 以您喜欢的任何ID 作为密钥添加它们,但您有责任确保密钥是唯一的。通常,出于这个原因,我们鼓励使用推送。
  • 我可以使用推送,但我如何在不使用 KbaZqVQBp580Zzt4Uty 的情况下查询游戏列表中的内容?
  • 您可以使用任何子值进行查询:game_namefirst_name 等。这是您的意思吗?

标签: javascript firebase ionic-framework firebase-realtime-database angularfire2


【解决方案1】:

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

获取 push-id 并将其存储在另一个节点中:

在 AngularFire 的 push 方法中有一种获取当前 push-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 方法而不是 push 来更改推送键:

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 可以通过第一种方法为您完成这项任务。

此外,如上面的 cmets 所述,您可以使用 random_id 子节点查询您的列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2012-09-23
    • 2014-02-03
    • 2011-06-15
    • 1970-01-01
    相关资源
    最近更新 更多