简体   繁体   中英

Create new if doesn't exist else update in firebase

I am using firebase as database for my mobile app created using 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.

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 ? And if they are not existed a new entry with "user1" or "user2" should be created with respective couponcode which they have entered.

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. 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 ? 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.

Here is my code on google cloud function as of now ! :

 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 ?

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."

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:

   .....
   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.

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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