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

时间:2018-04-24 07:53:43

标签: javascript firebase firebase-authentication google-cloud-firestore

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

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

}

3 个答案:

答案 0 :(得分:1)

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

}

答案 1 :(得分:0)

在向您提供答案之前,BEWARE云功能确实会花费不可预测的时间。因此,如果您需要立即开始使用用户集合中存储的数据,也许这不是您采取的正确方法。

使用firebase云功能。

exports.createUser = functions.auth.user().onCreate((user) => {
  const userMap = {
    uid: user.uid,
    email: user.email,
  };
  return admin.firestore().collection('user').doc(user.uid).set(userMap);
});

答案 2 :(得分:0)

您可以关联以下示例并生成代码

这里的 "_email","_password","_city","_phone" 是变量

onSaved: (value) => _email = value

取自 TextFormField() 函数

代码:

String userId = await widget.auth.createUserWithEmailAndPassword(_email, _password);

print('Registered user: $userId');

final new_user = await FirebaseFirestore.instance.collection('users').doc(userId).
      set({"UserUID":'$userId',"Email":_email,"Password":_password,"City":_city,"Phone 
Number":_phone});