2016-07-30 217 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,重现问题,我会看看。 –