【问题标题】:NextJS: `function` cannot be serialized as JSON. Please only return JSON serializable data typesNextJS: `function` 不能被序列化为 JSON。请仅返回 JSON 可序列化数据类型
【发布时间】:2022-02-07 03:43:26
【问题描述】:

我有一个名为“导师”的 Firestore 集合。集合中的每个文档都包含三个字段:“name”、“email”和“linkedin”。

我想获取集合中的所有文档并将它们作为道具传递。然后我想访问这些要在我的页面上呈现的文档字段。

我正在使用 getServerSideProps 在呈现页面之前获取 Firestore 数据。 我的代码如下:

dashboard.js:

import nookies from "nookies";
import { onSnapshot, getFirestore, collection, getDocs } from "firebase/firestore";

export default function dashboard({session,mentors}){
       return(
            //rendering each value in the mentors array
          )
}

export async function getServerSideProps(context) {
    try {
      const cookies = nookies.get(context);
      const token = await verifyIdToken(cookies.token);
      if (!token) {
        return {
          redirect: {
            permanent: false,
            destination: "/login",
          },
          props: {},
        };
      }
      const mentors = [];
      const db = getFirestore();
      const querySnapshot = await getDocs(collection(db, "mentor"));
        querySnapshot.forEach((doc) => {
            mentors.push({mentorID: doc.id, mentorData: doc.data})
          });
      return {
        props: {
          session: token,
          mentors,
        },
      };
    } catch (error) {
      context.res.writeHead(302, { location: "/login" });
      context.res.end();
      return { props: {} };
    }
  }

但是,我在控制台中收到以下错误:

error - Error: Error serializing `.mentors[0].mentorData` returned from `getServerSideProps` in "/dashboard".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.

我该如何解决这个问题?如果代码中有错误,请见谅。我对 JS 比较陌生。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore next.js


    【解决方案1】:

    doc.data 是一个函数,而不是实际的文档数据。为清楚起见,请参阅API documentation。您应该调用它以获取包含快照中数据的对象。

    mentors.push({mentorID: doc.id, mentorData: doc.data()})
    

    【讨论】:

    • 非常感谢。它奏效了。
    猜你喜欢
    • 2022-01-23
    • 2022-10-03
    • 2017-05-07
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    相关资源
    最近更新 更多