【问题标题】:Unhandled Rejection (FirebaseError): Function DocumentReference.update() called with invalid data. Unsupported field value: a custom object未处理的拒绝 (FirebaseError):使用无效数据调用函数 DocumentReference.update()。不支持的字段值:自定义对象
【发布时间】:2021-06-08 15:45:59
【问题描述】:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
import React, { useRef } from "react";
import firebase from "../api/firebase";
import admin from "firebase-admin";

export default function ListItem(props) {
  const commentRef = useRef();

  const addCommentHandler = async () => {
    const comment = commentRef.current.value;
    const db = firebase.firestore();
    // const jajaja = await db.collection("userData").doc(`${props.id}`).get();
    // console.log(jajaja.data().comments.length);
    const init = db.collection("userData").doc(`${props.id}`);

    const init2 = await init.update(
      { comments: admin.firestore.FieldValue.arrayUnion(`${comment}`) },
      {
        merge: true,
      }
    );
  };

  return (
    <>
      <li onClick={props.onClick}>{props.email}</li>
      <input type="text" ref={commentRef} />
      <button onClick={addCommentHandler}>Add Comment</button>
    </>
  );
}

我不断收到标题作为错误。我究竟做错了什么?另外,这是我的数据库的快照。我已经在 firestore 中添加了一条评论,并且正在尝试添加更多“cmets”数组项。

这是使用 set() 而不是 update() 后的错误

【问题讨论】:

    标签: javascript arrays reactjs google-cloud-firestore


    【解决方案1】:

    您在.update() 中传递{merge: true}。当您知道文档存在时使用更新方法,否则它将返回错误。

    const init2 = await init.set(
          { comments: admin.firestore.FieldValue.arrayUnion(`${comment}`) },
          {
            merge: true,
          }
        );
    

    您可能正在寻找.set()。如果不存在,它将创建一个文档,但会更新现有文档而不覆盖其他字段。

    如果您知道文档存在并且看起来像这样,最好的方法是使用更新:

    const init2 = await init.update({ comments:admin.firestore.FieldValue.arrayUnion(`${comment}`) }
    

    再次注意,使用更新时不需要传递合并选项。

    【讨论】:

    • 我得到了同样的错误,而不是 DocumentReference.update(),我得到了 DocumentReference.set()。此外,我可以正常添加原始数据类型,但数组和映射会导致问题。
    • @Darius 我想看看错误的截图。
    猜你喜欢
    • 2021-10-05
    • 2023-01-04
    • 2021-01-01
    • 2021-10-26
    • 2021-06-12
    • 2021-12-26
    • 2021-09-26
    • 2019-12-07
    相关资源
    最近更新 更多