當(dāng)需要從數(shù)據(jù)庫(kù)中返回一些數(shù)據(jù),然后使用它進(jìn)行一些計(jì)算并將其存儲(chǔ)回來(lái)時(shí),則需要使用事務(wù)性數(shù)據(jù)。
下面來(lái)看看運(yùn)動(dòng)員列表中的運(yùn)動(dòng)員。

我們要檢索屬性,添加年齡增加1歲并將其返還給Firebase。
amandaRef從集合中檢索年齡,然后可以使用事務(wù)方法。 我們將獲得當(dāng)前的年齡,增加一年,并更新集合。
<!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>
如果運(yùn)行這個(gè)代碼,可以看到年齡值更新為21。如下圖所示 -