How to retrieve data from Firebase using Javascrip

2020-06-05 04:34发布

问题:

I'm trying to access "id" and store it in a variable. So far the code I have is:

var ref = firebase.database().ref("users");

ref.on("value", function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var childData = childSnapshot.val();
    console.log(childData);
  });
});

What I get from above is:

With that I have access to the object itself, but how can I access the property "id"? I'm reading the official documentation but I can't figure it out.

回答1:

Do this:

 var ref = firebase.database().ref("users");

ref.on("value", function(snapshot) {
 snapshot.forEach(function(childSnapshot) {
  var childData = childSnapshot.val();
  var id=childData.id;
  console.log(childData);
 });
});

In the above the location is at users then you use on() method to read data, and using the forEach loop, you iterate inside the pushid and get the values.

To access each one alone you do this var ids=childData.id; or/and var names=childData.name;

Also it is better to use once() as it only reads data once.



回答2:

You need to get key of parent-node(L2L6vBsd45DFGfh) to access id child

When you use push() method in firebase it will automatic generate unique key for your record. use set() or update() method to create your own custom keys.

var ref = firebase.database().ref("users");
ref.on("value", function(snapshot) {
    var childData = snapshot.val();
    var key = Object.keys(childData)[0];    //this will return 1st key.         
    console.log(childData[key].id);
});

You will use for-loop or forEach to get all keys.