我试图在Firebase / Firestore中代替自动生成的文档ID的用户UID,但由于此错误而无法获取
TypeError:firebase.auth(...)。currentUser为null
这是我的index.js文件:
// Firestore Cloud Database
var db = firebase.firestore();
function reg(){
//window.alert("Working..!");
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;
//window.alert(txtname);
firebase.auth().createUserWithEmailAndPassword(txtEmail, txtPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
//alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
// Getting user id
var uid = firebase.auth().currentUser.uid;
//User Data Insertion
if(uid !=null){
db.collection("users").doc(uid).add({
UserName: txtname,
Email: txtEmail,
Password: txtPass
})
// .then(function(uid) {
// console.log("Document written with ID: ", uid);
// })
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
}
最佳答案
由于firebase.auth().createUserWithEmailAndPassword(...)
是异步函数,因此您必须等待其解析后才能继续。
您可以尝试以下方法:
// Firestore Cloud Database
var db = firebase.firestore();
function reg(){
//window.alert("Working..!");
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;
//window.alert(txtname);
firebase.auth().createUserWithEmailAndPassword(txtEmail,txtPass)
.then(function (user) {
// insert any document you want here
})
.catch(function(error) {
// handle error here
});
}
关于javascript - 如何在Firestore文档ID的位置添加用户UID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49996226/