Firebase寫入事務數據

當需要從數據庫中返回一些數據,然後使用它進行一些計算並將其存儲回來時,則需要使用事務性數據。

下面來看看運動員列表中的運動員。

Firebase寫入事務數據

我們要檢索屬性,添加年齡增加1歲並將其返還給Firebase。

amandaRef從集合中檢索年齡,然後可以使用事務方法。 我們將獲得當前的年齡,增加一年,並更新集合。

<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="utf-8" />
        <title>FireBase Example</title>
        <script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script>
        <script>
          // Initialize Firebase
          var config = {
            apiKey: "AIzaSyAOSPYpgn7T_bKa6VbCaSeQlsw-3p3zqDs",
            authDomain: "yiibai-firebase.firebaseapp.com",
            databaseURL: "https://yiibai-firebase.firebaseio.com/",
            projectId: "yiibai-firebase",
            storageBucket: "yiibai-firebase.appspot.com",
            messagingSenderId: "334522625008"
          };
          firebase.initializeApp(config);
          var amandaAgeRef = firebase.database().ref().child('players').child('Amanda').child('age');
          amandaAgeRef.transaction(function(currentAge) {
               return currentAge + 1;
            });
        </script>
    </head>
<body>

如果運行這個代碼,可以看到年齡值更新爲21。如下圖所示 -
Firebase寫入事務數據