'Get the auto-generated id - Firebase
I'm trying to retrieve the id of the element that I inserted in the database with .key
. However, it returns the user
value instead of the auto-generated id.
How can I get the auto-generated id ?
var mainText = document.getElementById("main-text");
var emailText = document.getElementById("emailtxt");
var prenom = document.getElementById("prenomtxt");
var submitBtn = document.getElementById("submitBtn");
var heading = document.getElementById("heading");
var firebaseHeadingref = firebase.database().ref().child("titre");
firebaseHeadingref.on('value', function(datasnapchot){
heading.innerText = datasnapchot.val();
})
function submitClick(){
var firebaseref = firebase.database().ref();
var messageText = mainText.value;
var txtmail = emailText.value;
var prenomtxt = prenom.value;
if(messageText == "" || txtmail == "" || prenomtxt == ""){
alert("Tous les champs doivent être remplis");
return;
}
firebaseref.child("user").push().set({name : messageText, prenom:prenomtxt ,email : txtmail});
var f = firebase.database().ref().child("user").orderByChild("email").equalTo(txtmail);
// firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
//
// console.log(pushed_user.key);
//
// });
f.on("value", function(datasnapchot){
var id = datasnapchot.val();
console.log(id);
});
// location.reload();
}
Solution 1:[1]
Try calling it like a function:
var id = datasnapchot.key();
Solution 2:[2]
When you push an element you can directly retrieve the auto generated ID without having to call a listener.
firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
console.log(pushed_user.key);
});
You can find another example here.
Solution 3:[3]
var newPostKey = firebaseref.child("user").push().set({name : messageText,prenom:prenomtxt ,email : txtmail}).key;
"newPostKey" will be your key
Solution 4:[4]
Try the following:
var ref = firebase.database().ref("users");
ref.push().on("value", function(snapshot) { snapshot.forEach(function(childSnapshot) {
var id = childSnapshot.key();
console.log(childSnapshot);
});
});
You need to loop using forEach
and then you will be able to retrieve the push key using key()
Solution 5:[5]
This worked for me
var id = datasnapchot.key;
Use datasnapchot.key instead of datasnapchot.key()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Marc Sloth Eastman |
Solution 2 | Troy Myers |
Solution 3 | Bruno Galvão |
Solution 4 | Peter Haddad |
Solution 5 | Asbar Ali |