簡體   English   中英

在 Firebase Auth 之后將用戶數據添加到 Firestore

[英]Adding user data into firestore after Firebase Auth

在創建新用戶時使用 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);
        });
}

我實現的上述代碼能夠將用戶數據添加到 firebase 身份驗證中,但是它不會將任何數據添加到 firestore 數據庫中。 有沒有更好的方法來實現這個 function?

您不能使用this.createNewUserData調用另一個 function 。 因此,您需要調用createNewUserData(firstname,lastname,email); 來自createUserWithEmailAndPasswordthen塊。

目前,它沒有將任何用戶數據添加到firestore數據庫的原因是沒有調用function createNewUserData 因此,一旦調用了 function,您至少會收到一個調用 firestore 來添加該用戶。

試試這個,告訴我它是否有效

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