简体   繁体   English

在 Firebase Auth 之后将用户数据添加到 Firestore

[英]Adding user data into firestore after Firebase Auth

I'm trying to add User data into Cloud Firestore after using Firestore Auth when a new user is created.在创建新用户时使用 Firestore Auth 后,我正在尝试将用户数据添加到 Cloud Firestore 中。

$("#signup_btn").click(function () {
    var firstname = document.getElementById("firstname").value;
    var lastname = document.getElementById("lastname").value;
    var email = document.getElementById("email_signup").value;
    var password = document.getElementById("password_signup").value;

    firebase.auth().createUserWithEmailAndPassword(email, password).then(cred=>{
        this.createNewUserData(firstname,lastname,email);
    }).catch(error =>{
        var user = firebase.auth().currentUser;

        user.delete();
        var errorMessage = error.message;

        window.alert("Error: "+ errorMessage);
    });
});


function createNewUserData(firstname, lastname, email){
    db.collection("users").add({
        firstname: firstname,
        lastname: lastname,
        email: email
    })
        .then(function (docRef) {
            console.log("Document written with ID: ", docRef.id);
        })
        .catch(function (error) {
            console.error("Error adding document: ", error);
        });
}

The above code I've implemented is able to add user data into the firebase Auth however it doesn't add any data into the firestore database.我实现的上述代码能够将用户数据添加到 firebase 身份验证中,但是它不会将任何数据添加到 firestore 数据库中。 Is there a better way to implement this function?有没有更好的方法来实现这个 function?

You cannot call another function using this.createNewUserData .您不能使用this.createNewUserData调用另一个 function 。 Thus, you need to call createNewUserData(firstname,lastname,email);因此,您需要调用createNewUserData(firstname,lastname,email); from the then block of createUserWithEmailAndPassword .来自createUserWithEmailAndPasswordthen块。

Currently,the reason that the it does not add any user data into the firestore database is that the function createNewUserData is not called.目前,它没有将任何用户数据添加到firestore数据库的原因是没有调用function createNewUserData So, once that function is called you will get at least a call to firestore to add that user.因此,一旦调用了 function,您至少会收到一个调用 firestore 来添加该用户。

Try this and tell me if it's working or not试试这个,告诉我它是否有效

firebase.auth().signInWithEmailAndPassword(email, password)
   .then(function(firebaseUser) {
        db.collection("users").add({
            firstname: firstname,
            lastname: lastname,
            email: email
        })
        .then(function (docRef) {
            console.log("Document written with ID: ", docRef.id);
        })
        .catch(function (error) {
            console.error("Error adding document: ", error);
        });
   })
  .catch(function(error) {
       // Error Handling
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM