Error serializing Next.js in getStaticProps function?

Viewed 4478

I'm using getStaticProps() function and I get this error for no reason:

Error: Error serializing .posts[0] returned from getStaticProps in "/". Reason: object ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types.

I'm also using a mongoDb database, the connectDb() function runs the mongoose.connect() function and connects to the database. also, the console.log()s return valid JSON format data, I don't know what is causing this issue, here is my code:

export const getStaticProps: GetStaticProps = async (
  context: GetStaticPropsContext
) => {
  await connectDb()
  const count = await PostModel.countDocuments()
  const posts = await PostModel.find()
  console.log(posts)
  console.log(count)
  return {
    props: { posts: posts, count: count },
    revalidate: 10,
  }
}
1 Answers

Use lean it will convert in a plain JavaScript object.

const posts = await PostModel.find().lean();

or you can try serialization via .toJSON

Related