如何在Firestore文档ID的位置添加用户UID [英] How to add user UID in the place of firestore document ID

查看:43
本文介绍了如何在Firestore文档ID的位置添加用户UID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm trying to get user UID in the place of auto generated document ID in Firebase/Firestore but can't get it because of this error

TypeError:firebase.auth(...).currentUser为空

这是我的index.js文件:-

this is my index.js file:-

// 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(...)是一个异步函数,您必须等待它解决在继续之前.

Since firebase.auth().createUserWithEmailAndPassword(...) is an async function, you have to wait for it to resolve before continuing.

您可以尝试以下操作:

// 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
        });

}

这篇关于如何在Firestore文档ID的位置添加用户UID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆