简体   繁体   English

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

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

I am using firebase as database for my mobile app created using react native. 我正在使用firebase作为使用react native创建的移动应用程序的数据库。 In one scenario , i need to check that if the child already presented ? 在一种情况下,我需要检查孩子是否已经出现? if not create a new child else update the existing child. 如果不创建新子级,则更新现有子级。

I have a tree named "CouponUsage", and it has all the users who used coupon code. 我有一棵名为“ CouponUsage”的树,它具有使用优惠券代码的所有用户。

The structure of the tree is as follows: 树的结构如下:

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

So, what i want is, i need to check if "user1" or "user2" already existed ? 所以,我想要的是,我需要检查“ user1”或“ user2”是否已存在? And if they are not existed a new entry with "user1" or "user2" should be created with respective couponcode which they have entered. 如果不存在,则应使用输入的优惠券代码创建带有“ user1”或“ user2”的新条目。

The whole scenario is, user will enter couponcode in the app, and i am validating the code and then once correct, the coupon code will be sent to google cloud function, and then the above said thing will happen. 整个场景是,用户将在应用程序中输入优惠券代码,我正在验证代码,然后更正后,优惠券代码将发送到google cloud功能,然后上述事情就会发生。 So, that once the user entered coupon code ( every coupon code has separate user usage limit ), the code will be sent , and the function should check if the "user1" is already exist and if exist, the user entered code already exist ? 因此,一旦用户输入了优惠券代码(每个优惠券代码都有单独的用户使用限制),则将发送该代码,并且该功能应检查“ user1”是否已经存在,如果存在,则用户输入的代码已经存在? And if that exist then just update the counter else create "user1" and add a child of "coupon1" ( coupon entered by user ) and then start the counter with 1. 如果存在,则只需更新计数器,否则创建“ user1”并添加“ coupon1”的子代(用户输入的优惠券),然后从1开始计数器。

Here is my code on google cloud function as of now ! 这是我到目前为止在Google Cloud Function上的代码! :

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

Its clearly updating the count, if i pass the count also. 如果我也通过计数,则它会清楚地更新计数。 How to implement the above said in firebase ? 如何在firebase中实现以上所说的?

It is actually quite easy. 实际上,这很容易。 Since you are updating a counter, you should use a Transaction , which while "modifying the existing value to a new value" will "ensure there are no conflicts with other clients writing to the same location at the same time." 由于要更新计数器,因此应使用Transaction ,它在“将现有值修改为新值”的同时,“将确保与其他同时写入相同位置的客户端没有冲突”。

The good news is that the transaction will automatically handle the case when the user/coupon pair does not exist. 好消息是,当用户/优惠券对不存在时,交易将自动处理该案件。

Here is the code to include in your Cloud Function: 这是要包含在您的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;
   });
   .....

If you want to test the transaction outside of a Cloud Function, just copy/paste the following code to an HTML file that you may save locally, change the Firebase config elements to your own ones and open it in a browser. 如果要在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