简体   繁体   中英

how to pull id from push() firebase?

Can someone please explain me why firebase unique id starting with '-' ?

I have two questions:

How can i get the id from push, if there is any return to this request?

firebase.database().ref('carts/-KJp9LdQkEN1DtuCLjfP/pro').push({
  name:name,
  amount:am
});

On this part i'm trying to handle the callback snapshot. All my attempt to extract the data from this json have failed.

JSON.parse(data) == error
snapshot.key(); == error
data[0] == error

firebase.database().ref('carts/').on('value', function(snapshot) {
  var data = snapshot.val();
  console.log(data);
});

These keys (often called "push ids") start with a - because that is the first character in the dictionary used to generate them. See this blog post explaining how they are generated .

If you are trying to get the push id of a item you're adding, you can do that like this:

var newRef = firebase.database().ref('carts/-KJp9LdQkEN1DtuCLjfP/pro').push();
console.log(newRef.key);
newRef.set({
  name:name,
  amount:am
});

If you want to determine the key of an item in a listener, you can do that like this:

firebase.database().ref('carts/').on('value', function(snapshot) {
  console.log(snapshot.key); // carts
  var data = snapshot.val();
  console.log(data);
});

More likely if you're listening for children, you'd get the key with this:

firebase.database().ref('carts/').on('child_added', function(snapshot) {
  console.log(snapshot.key); // -KJ....
  var data = snapshot.val();
  console.log(data);
});

Or like this:

firebase.database().ref('carts/').on('value', function(snapshot) {
  snapshot.forEach(function(cartSnapshot) {
    console.log(cartSnapshot.key); // -KJ....
    console.log(cartSnapshot.val());
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM