簡體   English   中英

Firestore:如何更新 email 並將其作為單個批處理操作存儲在我的 Firestore 集合中?

[英]Firestore: How do I update email and store it in my firestore collection as a single batch operation?

我正在編寫 react native 項目,用戶可以使用他們的usernamepassword 由於 firebase 身份驗證沒有使用usernamepassword登錄的功能,我做了一些小把戲。 在注冊時,我將用戶的email與其他有用的用戶信息一起存儲在我的Users集合中。 因此,當用戶嘗試使用username和密碼登錄時,我 go 到我的Users集合中,查找相應的username ,並獲取相應的email地址。 所以變相,我使用firestore方法.signInWithEmailAndPassword(email, password) 不理想,但它可以完成工作。

但是,問題是當用戶想要將他/她的 email 地址更新為新地址時。 然后,我肯定想更新我的用戶集合中的email值,以便我可以執行正確的登錄。這是更新用戶 email 的代碼:

const onChangeEmail = async () => {
    await firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(async function (userCredential) {
        await userCredential.user.updateEmail(newEmail).then(async () => {
          await updateEmailInFirestore(newEmail);
        });
      })
      .catch((error) => {
        console.log("Error while updating email: ", error);
      });
  };

updateEmailInFirestore在哪里執行以下操作:

export const updateEmailInFirestore = async (newEmail) => {
  if (!newEmail) {
    return;
  }
  await firebase
    .firestore()
    .collection("Users")
    .doc(firebase.auth().currentUser.uid)
    .update({ email: newEmail })
    .then(() => console.log("email was updated in user collection: ", newEmail))
    .catch((error) => console.log("error while updating email: ", error));
};

上面的代碼工作正常並完成了工作。 但是,我遇到的問題是以下情況:如果userCredential.user.updateEmail成功執行,但updateEmailInFirestore失敗或拋出異常怎么辦? 然后,我在數據庫中的值將與用戶更新的 email 地址不一致,我的登錄將失敗。

有沒有辦法我可以同時執行userCredential.user.updateEmailupdateEmailInFirestore作為批處理操作,這樣要么都成功,要么都失敗? 我之前寫過批處理操作,但它們的思路是const batch = firebase.firestore().batch(); 我的第一個操作與firestore無關,而是與firebase身份驗證有關?

在確保兩個承諾都得到解決時,您無能為力。 Firebase Auth 和 Firestore 是 2 個不同的產品,因此沒有像批量寫入這樣的概念。 您可以使用Promise.all()並要求用戶在任何一個承諾失敗時重試,如下所示。

const updateUserEmail = async () => {
  try {
    await Promise.all([
      user.updateEmail(newEmail),
      userDoc.update({
        email: newEmail
      })
    ])
  } catch (e) {
    console.log("Updating email failed")
    // prompt user to retry
  }
}

更好且廣泛使用的解決方案是創建格式為username@noreply.yourapp.com的 email 並將其與createUserWithEmailAndPassword()一起使用。 當用戶更新他們的用戶名時(如果您想允許該功能),那么您只需將 email 更新為newUsername@noreply.yourapp.com 如果您使用此方法,則不需要用於 email 的 Firestore。

請注意,您將無法使用驗證 email 等功能,因為這些 email 不存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM