【问题标题】:Firebase Cloud Functions onDelete problem - DatabaseFirebase Cloud Functions onDelete 问题 - 数据库
【发布时间】:2020-07-07 20:40:15
【问题描述】:

我在 Firebase 数据库中有以下结构,其中RoomsTemplate 是订阅室。如果有人注册Users 节点,另一个函数(onWrite)会增加CountUsers 的值。

当用户从节点Users退订时,下面的函数会减小CountUsers的值。

exports.recountUsers = functions.database.ref('/RoomsTemplate/{id}/CountUsers').onDelete(async (snap) => {
  const counterRef = snap.ref;
  const collectionRef = counterRef.parent.child('Users');
  const messagesData = await collectionRef.once('value');
  return await counterRef.set(messagesData.numChildren());
});

问题是,如果我想删除RoomsTemplate的主节点,在这种情况下

-MBb2ZKj-pquagHBqguS

onDelete 函数不允许我删除它,但它会再次更新CountUsers: 0。尝试先用另一个函数删除Barrio:"Barcelona"节点,然后验证并删除主节点。

exports.recountUsers = functions.database.ref('/RoomsTemplate/{id}/CountUsers').onDelete(async (snap) => {
  const counterRef = snap.ref;
  const collectionRef = counterRef.parent.child('Users');  
  const messagesData = await collectionRef.once('value');

  const Barrio = await counterRef.parent.child('Barrio').once('value');

   if(Barrio.numChildren() === 0){
     return await counterRef.remove();
   }else if(Barrio.numChildren() > 0){
     return await counterRef.set(messagesData.numChildren());
   }else{
     return null;
   } 

});

但我仍然有同样的存在问题。 如何在不执行onDelete函数的情况下永久删除主节点(-MBb2ZKj-pquagHBqguS)?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    我的第一个想法是,您在这里将自己建模为一个问题,没有遵循保持数据结构平坦的指导。基于此,我推荐的解决方案是进一步非规范化数据,并将计数拉入单独的顶级列表。事实上,我在这里看到了三个顶级列表:

    RoomsTemplate
      $roomid: { Barrio: "..." }
    },
    RoomsTemplate_users: {
      $roomid: { "uid1" true, "uid2": true }
    },
    RoomsTemplate_usercounts: {
      $roomid: 2
    }
    

    或者,在您当前的数据结构中,您可以在编写计数器之前检查房间是否仍然存在。例如,第一个云函数看起来像:

    exports.recountUsers = functions.database.ref('/RoomsTemplate/{id}/CountUsers').onDelete(async (snap) => {
      const counterRef = snap.ref;
      const roomRef = counterRef.parent;
      const roomSnapshot = await roomRef.once("value");
      if (roomSnapshot.exists()) {
        const messagesData = roomSnapshot.child("Users");
        await counterRef.set(messagesData.numChildren());
      }
      return true;
    });
    

    由于 Cloud Functions 在原始写入完成后异步执行,因此 once('value'(就像您已经拥有的 collectionRef 一样)将始终从数据库中获取当前快照,即房间消失的位置。

    【讨论】:

    • 对!这里的问题是它从不咨询存在......我将这些条件添加到 onWrite 和 onDelete 函数中,瞧!谢谢!
    猜你喜欢
    • 2019-10-03
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 2020-09-01
    • 2021-10-06
    • 2021-01-09
    • 1970-01-01
    • 2017-10-10
    相关资源
    最近更新 更多