【问题标题】:How can I create a incremental ID for Firebase realtime database?如何为 Firebase 实时数据库创建增量 ID?
【发布时间】:2020-04-23 12:08:01
【问题描述】:

所以在我的实时数据库中它看起来像:

ss: {
  xx: {
    id: 1
  },
  yy: {
    id: 2
  },
  ...
}

我尝试首先获取具有最大 ID FirebaseRef.child('ss').orderByChild('id').limitToLast(1) 的孩子,然后为检索到的值执行 +1.. 然后 push 新记录。但这可能会导致 id 加倍,因为在 fetch 和 push 之间,其他人可以创建新记录。我查看了transaction 功能,但不知道必须在我的场景中使用它(因为它只检索和更新值?)。

【问题讨论】:

标签: javascript firebase firebase-realtime-database


【解决方案1】:

一种可能的方法是维护一个计数器,每次需要生成新的 id 时,在 transaction 中增加这个计数器并读取值:

以下应该可以解决问题:

  //Declare a function that increment a counter in a transaction
  function getId() {
    var counterRef = firebase.database().ref('counter');
    return counterRef.transaction(function(currentId) {
      return currentId + 1;
    });
  }


  //Call the asynchronous getID() function
  getId().then(function(transactionResult) {
    var newId = transactionResult.snapshot.val();
    console.log(newId);
    firebase.database().ref('ss/xx').set({id: newId});
  });

您不需要创建counter 节点,它会在第一次调用getId() 函数时自动创建。

【讨论】:

  • 在没有柜台的情况下,您确定return currentId + 1; 就足够了吗?我通常会做return (currentId || 0) + 1;
  • @FrankvanPuffelen 在来自documentation 的示例中是这样做的,并且明确提到“// 如果用户/ada/rank 从未设置,currentRank 将为null”。
  • 那部分我知道。但我从未意识到null + 1 = 1。哦,JavaScript,你这个神奇的野兽。 :-D
  • true + null = 1 也是一个“有趣的”... :-)
猜你喜欢
  • 2019-09-02
  • 2021-07-22
  • 2021-09-20
  • 2021-08-24
  • 2021-08-31
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 2020-01-20
相关资源
最近更新 更多