2016-07-30 216 views
0

我正在嘗試學習新的Firebase,並且正在跟隨其網站上的指南,但我只是沒有弄清楚這部分內容。如何將數據保存到數據庫?目前我的數據庫是空的,我想要發生的事情是用戶在文本輸入中鍵入內容,然後點擊保存,並且應該保存用戶輸入到數據庫的任何內容以及他的UId和數據的dateCreated。下面是我的了:Firebase - 將數據保存到數據庫

<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script> 
<script> 
    // Initialize Firebase. Note that I'm not using the real init details in this post but I assure you they are present in my app 
    var config = { 
     apiKey: "myApiKey", 
     authDomain: "myProject.firebaseapp.com", 
     databaseURL: "https://myProject.firebaseio.com", 
     storageBucket: "myProject.appspot.com", 
    }; 
    firebase.initializeApp(config); 
    var database = firebase.database() 

    // A whole bunch of other unrelated functions and stuff here 

    $('#addMeal').click(function() { 
     $('#addBox').slideUp(); 
     var meal = $('#txtAdd'); var uid = $('#uid').val(); 
     // If I try to console.log these two vars up here it does actually fire so I don't think there's something wrong with the jquery. 

     if(meal.val()) { 

     function createMeal(uid, email) { 
      firebase.database().ref('meals/').set({ 
      title: name, 
      user: uid, 
      dateCreated: new Date() 
      }); 
     } 

     } else { 
     $('#addBox').addClass('margin_top_xs alert alert-danger').slideDown(); 
     $('#addMsg').html('<h5 class="centered bold margin_bot_no"> You can\'t enter a blank meal!</h5>'); 
     } 
    }); 

</script> 

也請記住,我真的不知道該寫我應該使用方法,我想要做的就是保存每餐分貝,不保存於其他任何數據,因此如果您使用不同的方法保存數據,我不介意。

任何幫助,將不勝感激。謝謝!

回答

1

這聽起來像你想保持一頓飯的清單。因此,而不是調用set,它(因爲它名字所暗示的),在數據庫中的位置設置數據,你應該叫push()appends the data to a list of data

function createMeal(uid, email) { 
     firebase.database().ref('meals/').push({ 
     title: name, 
     user: uid, 
     dateCreated: new Date() 
     }); 
    } 

我鏈接的文檔中詳細說明了這一點,所以我建議(重新)閱讀它。

+0

謝謝你,但它沒有奏效。我的數據庫仍然是空的:( – PrintlnParams

+0

將附加數據保存到類似列表的位置需要使用push(),這可能是由許多問題引起的,我從您發佈的代碼中可以很容易地看到這些問題。發佈一個**最小** jsfiddle/jsbin,重現問題,我會看看。 –