2017-02-26 133 views
1

我正在編寫一個小應用程序,其中有一個評分系統(例如10個用戶),我正在通過Firebase數據庫進行此操作。如何通過Javascript更新Firebase元素?

我的問題是,我不知道如何更新我在開始時創建的數據庫元素。我想通過一個可以觸發的Javascript腳本更新我的觀點。

所以這是我當前的代碼:

var rootRef = firebase.database().ref(); 

VAR用戶= rootRef.child( 「用戶」);

var log = document.getElementById('log');

document.getElementById('registerBtn').addEventListener('click', function(event) { 

     var empt1 = document.forms["form1"]["email"].value; 
     var empt2 = document.forms["form1"]["password"].value; 
     var empt3 = document.forms["form1"]["email"].value; 

     if(empt1 == "" || empt2 == "" || empt3 == "" || !document.getElementById("txtemail").checkValidity()){ 
      alert("Something went wrong!"); 
     } 
     else{ 
      $("#registerProgress").show(); 
      $("#registerBtn").hide(); 
      //Get email and pass 
      const email = txtemail.value; 
      const pass = txtpassword.value; 
      const username = txtusername.value; 
      const auth = firebase.auth(); 

      const promise = auth.createUserWithEmailAndPassword(email, pass); 
      promise.catch(e => console.log(e.message)); 
      //users.child(username).set({ name: username }); 
      users.once('value', function(snapshot) { 
       if (!snapshot.hasChild(username)) { 
        users.child(username).set({username: username, points: "100"}); 
       } 
       else { 
        alert("That username is already registered"); 
       } 
      }); 
     } 
    }); 

在此先感謝!

回答

0

我想你問的只是在用戶不存在的情況下如何更新Firebase中的用戶記錄?假設火力的3.xx:

var usersRef = firebase.database().ref().child('users'); 

usersRef.child(username).once('value') 
    .then(function (userRecord) { 
    if(userRecord.exists()) { 
     alert('That username is already registered'); 
    } else { 
     //--> There's a ref in each snapshot 
     userRecord.ref.child('username').set(username) 
     .then(function() { 
      userRecord.ref.child('points').set(100); 
     }); 
    } 
    }); 

添加點:

usersRef.child(username).child('points').transaction(function (points) { 
    return (points || 0) + 10; 
}); 

Official Reference mentioning transactions

注意:不要忘記保存一個數字(100),而不是一個字符串( 「100」)或增量器將無法正常工作。祝你好運。

+0

但是每次用戶喜歡贏得關卡時,他應該得到10分 - >這應該在數據庫中更新 – Zoruak

+0

更新爲這樣做。 – deezy

+0

非常感謝你!!!!!! – Zoruak