未处理的拒绝与 FieldValue.arrayUnion()

时间:2021-04-14 02:33:47

标签: reactjs firebase google-cloud-firestore

我正在制作一个社交媒体克隆,当我尝试关注另一个个人资料时,我遇到了一个错误。当我尝试使用 console.log("follow user") 时,它会正常工作,但是当我将其更改为 onClick={handleFollowUser} 时,它会抛出一个错误,指出某些内容未定义。

您可以在此处查看具体错误:https://imgur.com/Lit4iqv

我得到的错误是:

<块引用>

未处理的拒绝 (FirebaseError):使用无效数据调用函数 FieldValue.arrayUnion()。不支持的字段值:未定义(在文档 users/pX1fay49L6fLiYwnzIXL 中找到)

  async function handleFollowUser() {
    setFollowed(true);
    await updateLoggedInUserFollowing(loggedInUserDocId, profileId, false);
    await updateFollowedUserFollowers(profileDocId, userId, false);
  }

      <button
        className="text-xs font-bold text-blue-medium"
        type="button"
        onClick={handleFollowUser}
        // onClick={console.log('Follow this user!')}
      >
        Follow
      </button>
  export async function updateLoggedInUserFollowing(
    loggedInUserDocId, // currently logged in user document id (gore's profile)
    profileId, // the user that gore requests to follow
    isFollowingProfile // true/false (am i currently following this person?)
  ) {
    return firebase
      .firestore()
      .collection('users')
      .doc(loggedInUserDocId)
      .update({
        following: isFollowingProfile ? FieldValue.arrayRemove(profileId) : FieldValue.arrayUnion(profileId)
      });
  }
  
  export async function updateFollowedUserFollowers(
    profileDocId, // currently logged in user document id (gore's profile)
    loggedInUserDocId, // the user that gore requests to follow
    isFollowingProfile // true/false (am i currently following this person?)
  ) {
    return firebase
      .firestore()
      .collection('users')
      .doc(profileDocId)
      .update({
        followers: isFollowingProfile
          ? FieldValue.arrayRemove(loggedInUserDocId)
          : FieldValue.arrayUnion(loggedInUserDocId)
      });
  }

1 个答案:

答案 0 :(得分:0)

正如 @Frank van Puffelend 所说,您试图将未定义的值写入数据库,这将引发错误。您可以通过多种方式修复,一种是让 Firebase 忽略未定义的值。一个例子是:

import * as firestore from "firebase-admin"

const db = firestore.firestore();
db.settings({ ignoreUndefinedProperties: true })

相关问题