繁体   English   中英

如果不存在则创建新的,否则在firebase中更新

[英]Create new if doesn't exist else update in firebase

我正在使用firebase作为使用react native创建的移动应用程序的数据库。 在一种情况下,我需要检查孩子是否已经出现? 如果不创建新子级,则更新现有子级。

我有一棵名为“ CouponUsage”的树,它具有使用优惠券代码的所有用户。

树的结构如下:

   -CouponUsage
       -user1
          -coupon1: 0    // couponcode name and Number of times used
       -user2
          -coupon1: 2
          -coupon2: 0

所以,我想要的是,我需要检查“ user1”或“ user2”是否已存在? 如果不存在,则应使用输入的优惠券代码创建带有“ user1”或“ user2”的新条目。

整个场景是,用户将在应用程序中输入优惠券代码,我正在验证代码,然后更正后,优惠券代码将发送到google cloud功能,然后上述事情就会发生。 因此,一旦用户输入了优惠券代码(每个优惠券代码都有单独的用户使用限制),则将发送该代码,并且该功能应检查“ user1”是否已经存在,如果存在,则用户输入的代码已经存在? 如果存在,则只需更新计数器,否则创建“ user1”并添加“ coupon1”的子代(用户输入的优惠券),然后从1开始计数器。

这是我到目前为止在Google Cloud Function上的代码!

 if(usersCouponUsage) {
            await admin.database().ref(`couponUsage/${phone}`)
            .update({ [couponCodeName]: usersCouponUsage + 1 });
        }

如果我也通过计数,则它会清楚地更新计数。 如何在firebase中实现以上所说的?

实际上,这很容易。 由于要更新计数器,因此应使用Transaction ,它在“将现有值修改为新值”的同时,“将确保与其他同时写入相同位置的客户端没有冲突”。

好消息是,当用户/优惠券对不存在时,交易将自动处理该案件。

这是要包含在您的Cloud Function中的代码:

   .....
   const user = 'user1';  //Set the user
   const coupon = 'coupon1'  //Set the coupon

   const couponUsageRef = admin.database().ref('CouponUsage/' + user + '/' + coupon);

   return couponUsageRef.transaction(currentNbr => {
      return currentNbr + 1;
   });
   .....

如果要在Cloud Function外部测试事务,只需将以下代码复制/粘贴到您可以在本地保存的HTML文件中,将Firebase config元素更改为您自己的元素,然后在浏览器中将其打开。

<!DOCTYPE html>
<html lang="en-US">
<head>

    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, user-scalable=yes">

    <script src="https://www.gstatic.com/firebasejs/5.9.0/firebase.js"></script>


</head>

<body>

    <script>

        var config = {
            apiKey: "--yourValue--",
            authDomain: "--yourValue--",
            databaseURL: "--yourValue--",
            projectId: "--yourValue--"
        };


        firebase.initializeApp(config);

        var user = 'user1';
        var coupon = 'coupon2'
        var db = firebase.database();
        var couponUsageRef = db.ref('CouponUsage/' + user + '/' + coupon);

        couponUsageRef.transaction(function(currentNbr) {

           return currentNbr + 1;
        });

    </script>

</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM