[英]Get the auto-generated id - Firebase
I'm trying to retrieve the id of the element that I inserted in the database with .key
.我正在尝试使用.key
检索我插入到数据库中的元素的 ID。 However, it returns the user
value instead of the auto-generated id.但是,它返回user
值而不是自动生成的 id。
How can I get the auto-generated id ?如何获取自动生成的 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();
}
When you push an element you can directly retrieve the auto generated ID without having to call a listener.当您推送一个元素时,您可以直接检索自动生成的 ID,而无需调用侦听器。
firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
console.log(pushed_user.key);
});
尝试像函数一样调用它:
var id = datasnapchot.key();
var newPostKey = firebaseref.child("user").push().set({name : messageText,prenom:prenomtxt ,email : txtmail}).key;
“newPostKey”将是你的钥匙
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()
您需要使用forEach
循环,然后您将能够使用key()
检索推送密钥
This worked for me这对我有用
var id = datasnapchot.key;
Use datasnapchot.key instead of datasnapchot.key()使用datasnaphot.key代替datasnaphot.key()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.