You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Firebase苹果登录时如何判断Firestore用户存在避免数据覆盖

解决方法

你可以通过两种方式实现仅首次登录写入用户文档,避免重复覆盖:

方案1:通过Auth返回的新用户标识判断(推荐)

Firebase Auth登录成功后返回的凭证里自带isNewUser字段,可直接判断用户是否是首次注册,只有新用户才执行Firestore写入逻辑,避免覆盖旧数据,代码修改量最小:

appleSignIn: async () => {
  try {
    const appleAuthRequestResponse = await appleAuth.performRequest({
      requestedOperation: appleAuth.Operation.LOGIN,
      requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
    });
    if(!appleAuthRequestResponse.identityToken) {
      throw 'Apple Sign-In failed - no identify token returned';
    }
    const { identityToken, nonce } = appleAuthRequestResponse;
    const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
    // 接收登录返回的凭证信息
    const userCredential = await auth().signInWithCredential(appleCredential);
    // 仅新用户执行写入逻辑
    if (userCredential.additionalUserInfo.isNewUser) {
      await firestore().collection('users').doc(auth().currentUser.uid)
      .set({
        fname: appleAuthRequestResponse.fullName?.givenName || '',
        lname: appleAuthRequestResponse.fullName?.familyName || '',
        email: appleAuthRequestResponse.email || '',
        createdAt: firestore.Timestamp.fromDate(new Date()),
        userImg: null,
      })
    }
  } catch (e) {
    console.log(e);
  }
},

方案2:先查询文档是否存在再写入

如果你需要更灵活的判断逻辑,可以先拉取对应uid的文档判断是否存在,不存在再执行写入:

// 登录成功后新增判断逻辑
const userDocRef = firestore().collection('users').doc(auth().currentUser.uid);
const userDocSnapshot = await userDocRef.get();
if (!userDocSnapshot.exists) {
  await userDocRef.set({
    fname: appleAuthRequestResponse.fullName?.givenName || '',
    lname: appleAuthRequestResponse.fullName?.familyName || '',
    email: appleAuthRequestResponse.email || '',
    createdAt: firestore.Timestamp.fromDate(new Date()),
    userImg: null,
  })
}

注意事项

苹果登录仅会在用户首次授权应用时返回邮箱、姓名字段,后续重复调用登录接口这两个字段都会返回null,不要尝试后续登录时补全用户信息,必须保证首次登录时写入成功。

内容的提问来源于stack exchange,提问作者Kevin Tucker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:36:04