Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get firebase id

Anyone know how to get the Firebase unique id? I've tried name(), name, key, key(). Nothing works.

I am able to see the data but I have no idea how to get the id back. I need it.

//Create new customers into firebase 
function saveCustomer(email) {

  firebase.database().ref('/customers').push({
    email: email
  });

  firebase.database().ref('/customers').on("value", function(snapshot) {
    console.log(snapshot.val());
    console.log(snapshot.value.name());
  }, function(errorObject) {
    console.log("The read failed: " + errorObject.code);
  });


}
like image 318
user3183411 Avatar asked Aug 14 '16 05:08

user3183411


2 Answers

The call to push will return a Firebase reference. If you are using the Firebase 3 API, you can obtain the unique key of the pushed data from the reference's key property:

var pushedRef = firebase.database().ref('/customers').push({ email: email });
console.log(pushedRef.key);

The key for the pushed data is generated on the client - using a timestamp and random data - and is available immediately.

like image 91
cartant Avatar answered Oct 12 '22 10:10

cartant


Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it.

The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated:

// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();

Documentation.

like image 31
Dmitry Kalinin Avatar answered Oct 12 '22 10:10

Dmitry Kalinin