How to add user UID in the place of firestore document ID

隐身守侯 提交于 2021-01-24 11:42:45

问题


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 is null

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

}

回答1:


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

You can try this:

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

}



回答2:


Before I present you with my answer, BEWARE cloud functions do take unpredictable amount of time to process. So if you need to immediately start using the data stored in the users collection, maybe it's not the right method for you to take.

Using firebase cloud functions..

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



回答3:


You can relate the below example and generate your code

Here "_email","_password","_city","_phone" are variables for

onSaved: (value) => _email = value

taken from TextFormField() function

Code:

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


来源:https://stackoverflow.com/questions/49996226/how-to-add-user-uid-in-the-place-of-firestore-document-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!