【问题标题】:Firebase cloud function transaction remove node if count hits 0如果计数达到 0,Firebase 云功能事务删除节点
【发布时间】:2019-11-13 19:26:19
【问题描述】:

我有以下功能:

exports.tagCountDecrement = functions.database
 .ref('/categoryTags/{tagName}/{postId}')
 .onDelete((snapshot, context) => {

  const tagsWithCountRef = admin
    .database()
    .ref('tags')
    .child(context.params.tagName);

  return tagsWithCountRef
    .transaction(counter_value => {
      return (counter_value || 0) - 1;
    })
}) 

为了确保用户不会通过其键(值为 0)加载节点,如果计数达到 0,我想将其完全删除。我曾考虑将 0 替换为 null,但它需要一个数字如果节点不存在则开始。

通过 firebase 云功能解决这个问题最简单的方法是什么?

干杯。

【问题讨论】:

    标签: node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    你没有提供你的数据,所以我假设它看起来像这样:

    {
      "categoryTags" : {
        "id1" : {
          "post" : "postpostpost"
        },
        "id2" : {
          "post1" : "postpostpost",
          "post2" : "postpostpost"
        }
      },
      "tags" : {
        "id1" : 1,
        "id2" : 2
      }
    }
    

    在这种情况下,要删除节点而不是让计数为零,只要值为 1(或更小,或不存在,因为我想不出任何合理的做法,您需要从事务中返回 null在那些情况下,除了可能记录某种错误):

    exports.tagCountDecrement = functions.database.ref('/categoryTags/{tagName}/{postId}')
      .onDelete((snapshot, context) => {
        const tagsWithCountRef = admin
          .database()
          .ref('tags')
          .child(context.params.tagName)
    
        return tagsWithCountRef
          .transaction((current_value) => {
            if (!current_value || current_value <= 1) {
              // in either of these cases, delete (or leave it alone)
              return null;
            } else {
              // otherwise, reduce by 1
              return current_value - 1;
            }
          });
      });
    

    【讨论】:

    • 你猜对了数据库结构哈哈,就像一个魅力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-14
    • 2017-11-23
    • 2018-06-25
    • 2021-12-08
    • 2020-10-10
    • 2020-03-28
    • 2018-05-18
    • 2019-03-07
    相关资源
    最近更新 更多