我正在使用NextJS,之前我使用fetch()
调用内部/api
路由来获取数据。但是,我意识到在生产环境中,它不允许你在getServerSideProps
中使用内部api调用。因此,我试图直接从getServerSideProps
调用我的MongoDB数据库。
我的问题是,我得到了一个错误,我的posts
数据作为props
传递时不可序列化: "对象("[object Object]")无法作为JSON序列化。请仅返回可序列化的JSON数据类型."
我不明白为什么会出现这个问题,因为它的形式为:[object Object],[object Object],[object Object]等
,当它被传递时应该可以工作?
以下是我的代码供参考(代码下面有解释):
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"}, 等等。]
这个格式是否与我作为props传递的posts
匹配?
行console.log("RESULT: " + result)
打印:[object Object],[object Object],[object Object],[object Object], 等等。
@jabaa的答案:将返回更改为此行:startingPosts: JSON.parse(JSON.stringify(posts))