Javascript 如何从 Firebase 数据库中检索数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38541098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:35:26  来源:igfitidea点击:

How to retrieve data from Firebase Database?

javascriptfirebasefirebase-realtime-database

提问by gegobyte

I'm trying to create a simple program that takes name, mobile number and email address from user and then puts the data on Firebase Realtime Database.

我正在尝试创建一个简单的程序,该程序从用户那里获取姓名、手机号码和电子邮件地址,然后将数据放在 Firebase 实时数据库中。

There are 3 input boxes and a button which on click does the above operation. Here is the code:

有 3 个输入框和一个按钮,单击时执行上述操作。这是代码:

<input type="text" id="name">
<input type="text" id="mobile">
<input type="text" id="email">

<button type="button" id="button" onclick="addLead()">Submit</button>

I've set up Firebase like this:

我已经像这样设置了 Firebase:

<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    ...
  };
  firebase.initializeApp(config);

  var database = firebase.database();
</script>

And here is my addLead()function:

这是我的addLead()功能:

function addLead() {
    var clientName = document.getElementById('name').value;
    var clientMobile = document.getElementById('mobile').value;
    var clientEmail = document.getElementById('email').value;

    var newClientKey = database.ref().child('leads').push().key;
    database.ref('leads/'+newClientKey+'/name').set(clientName);
    database.ref('leads/'+newClientKey+'/mobile').set(clientMobile);
    database.ref('leads/'+newClientKey+'/email').set(clientEmail);
}

This is how I put data to database which works.

这就是我将数据放入有效数据库的方式。

enter image description here

在此处输入图片说明

So the newClientKeyis generating some string, it works well when inserting but now how to retrieve? The official documentationis of no help. This generated string might be based on timestamp, if that's the case then generating it again would be impossible.

所以newClientKey正在生成一些字符串,它在插入时效果很好,但现在如何检索?该官方文档是没有帮助的。这个生成的字符串可能基于时间戳,如果是这样,那么再次生成它是不可能的。

When retrieving how will I get access to email, mobile and name under that uniquely generated string which was only available at the time of inserting?

检索时,我将如何访问仅在插入时可用的唯一生成的字符串下的电子邮件、手机和姓名?

Going by the above structure, I need to get 2 levels down to access the required data and because of the lack of documentation, I don't know how to do that, I'm not sure if something like this will work:

按照上述结构,我需要降低 2 个级别才能访问所需的数据,并且由于缺少文档,我不知道该怎么做,我不确定这样的事情是否可行:

database.child().child();

回答by gegobyte

The answer to this question is buried deep within Firebase Database Reference. forEach()is used to get to the child without knowing the child's exact path.

这个问题的答案深埋在 Firebase数据库参考中forEach()用于在不知道孩子的确切路径的情况下到达孩子。

var leadsRef = database.ref('leads');
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var childData = childSnapshot.val();
    });
});

Now childSnapshotwill contain the required data, the same thing can also be accessed using child_added.

现在childSnapshot将包含所需的数据,同样的事情也可以使用child_added.

leadsRef.on('child_added', function(snapshot) {
      //Do something with the data
});

The only difference is that in case of forEach(), it will loop through from the start so if any new data will be added, it will also load the previous data but in case of child_added, the listener is only on new child and not the previous existing childs.

唯一的区别是,在 的情况下forEach(),它将从头开始循环,因此如果添加任何新数据,它也会加载以前的数据,但在 的情况下child_added,侦听器仅在新孩子上,而不是在以前的现有孩子上.

回答by Jortega

You could also use dot notation to get the value of the child you are looking for for.

您还可以使用点表示法来获取您正在寻找的孩子的价值。

Below I just commented out the forEach loop from the highest rated answer and added a console.log().

下面我只是从评分最高的答案中注释掉了 forEach 循环,并添加了一个 console.log()。

 var leadsRef = database.ref('leads');
  leadsRef.on('value', function(snapshot) {
      // snapshot.forEach(function(childSnapshot) {
        var childData = snapshot.node_.children_.root_.value.value_;
        console.log("snapshot.node_.children_.root_.value.value_: ", snapshot.node_.children_.root_.value.value_)
      // });
  });

At the time of posting this I am using firebase 5.9.1

在发布此内容时,我使用的是 firebase 5.9.1

src="https://www.gstatic.com/firebasejs/5.9.1/firebase.js"

src="https://www.gstatic.com/firebasejs/5.9.1/firebase.js"

回答by aniketwattamwar

var reference = db.ref('/test/');
reference.on('value', function(snapshot) {
snapshot.forEach(function(userSnapshot){
console.log(userSnapshot.val().url)
document.getElementById('gmap').href = userSnapshot.val().location;
document.getElementById('gimg2').src = userSnapshot.val().url;
document.getElementById('name').innerHTML = userSnapshot.val().uid;

I was facing the same issue. I wanted to read the data from the firebase realtime database and print the same on the web. The data I am reading is in the test document. Use the on()function to take the snapshot of it. Firebase provides you with a foreach loop to iterate over the data in the test document. The variable userSnapshotreads the value while looping. The variables location, url, uidare the keys in the test document.

我面临着同样的问题。我想从 firebase 实时数据库读取数据并在网络上打印相同的数据。我正在阅读的数据在测试文档中。使用该on()函数拍摄它的快照。Firebase 为您提供了一个 foreach 循环来迭代测试文档中的数据。该变量userSnapshot在循环时读取值。变量位置urluid是测试文档中的钥匙。

document.getElementById('gmap').href
document.getElementById('gimg2').src 
document.getElementById('name').innerHTML

are the DOM element to print the data on the web

是用于在 Web 上打印数据的 DOM 元素

<a id="gmap" class="btn btn-success btn-sm float-right" type="button" 
 role="button">See location </a>
 <p id="name"></p>
 <img id="gimg2" class="img-fluid"/>

I hope this helps someone.

我希望这可以帮助别人。