我正在使用 NextJS,我之前/api
使用.fetch()
getServerSideProps
getServerSideProps
我的问题是我得到的错误是我posts
传递的数据props
不可序列化:“对象(“[object Object]”)不能序列化为 JSON。请仅返回 JSON 可序列化数据类型。”
我不明白为什么,因为它的形式是:[object Object],[object Object],[object Object], etc.
通过时哪个应该起作用?
我的代码如下供参考(代码下方的解释):
export async function getServerSideProps() {
let returnID = null
let posts = []
let error = false
try {
const client = await MongoClient.connect(`mongodb+srv://MYUNIQUEMONDODBCONNECTIONDATA`);
const db = client.db();
const postsCollection = db.collection("posts");
const result = await postsCollection.find({}).limit(10).toArray();
console.log("RESULT: " + result)
client.close();
posts = result.map(r => {
return {
title: r.title,
body: r.body,
id: r._id,
}
});
if (posts[posts.length - 1]?.id) { // make sure it's not undefined
returnID = posts[posts.length - 1]?.id;
}
}
catch (error) {
error = true
}
return {
props: {
startingID: String(returnID),
startingError: error,
startingPosts: posts,
}
}
}
我从数据库收到的数据大致如下:[{"title":"1","body":"1","id":"6276767ca21167f5043d3dc8"},{"title":"2","body":"2","id":"6276767fa21167f5043d3dc9"},{"title":"3","body":"3","id":"62767682a21167f5043d3dca"}, etc.]
这不符合我posts
作为props传递的格式吗?
该行console.log("RESULT: " + result)
打印:[object Object],[object Object],[object Object],[object Object], etc.
来自@jabaa 的回答:将返回更改为这一行:startingPosts: JSON.parse(JSON.stringify(posts))