Suhaib
Suhaib

Reputation: 2061

'undefined' error when trying to access Firebase DB using JavaScript

This is what I have saved in DB enter image description here

This is my code which I used to try to access the data.

The goal is to get the value of the 1st id

var ref = db.ref("server/events/data");
ref.once("value", function(snapshot) { 

  var ids = snapshot.val();
  console.log(ids.id);

});

What am I missing ?

Upvotes: 0

Views: 288

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599081

Alternative to Dinesh' answer is looping over all results:

var ref = db.ref("server/events/data");
ref.once("value", function(snapshot) { 
  snapshot.forEach(function(childSnapshot) {
    var value = childSnapshot.val();
    console.log(value.id);
  });
});

Or accessing only a specific index:

var ref = db.ref("server/events/data/0");
ref.once("value", function(snapshot) { 
  var value = snapshot.val();
  console.log(value.id);
});

Upvotes: 1

Dinesh undefined
Dinesh undefined

Reputation: 5546

You should specify the index to access

  var ref = db.ref("server/events/data");
    ref.once("value", function(snapshot) { 

      var ids = snapshot.val();
      console.log(ids[0].id);

    });

Upvotes: 2

Related Questions