如何在 Firestore 文档 ID 的位置添加用户 UID

JM0*_*007 2 javascript firebase firebase-authentication google-cloud-firestore

我正在尝试在 Firebase/Firestore 中获取用户 UID 代替自动生成的文档 ID,但由于此错误而无法获取

类型错误:firebase.auth(...).currentUser 为空

这是我的 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);
});
}

}
Run Code Online (Sandbox Code Playgroud)

小智 5

由于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
        });

}
Run Code Online (Sandbox Code Playgroud)