【发布时间】: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