4

I'm trying to load data from mongodb into nextjs but keep recieving this error. The data has been entered the database by Python pymongo.

SerializableError: Error serializing .jobs[0] returned from getServerSideProps in "/". Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

enter image description here

Here is my function:

export async function getServerSideProps(context) {
  const { db } = await connectToDatabase();

  const data = await db
    .collection("alljobs")
    .find()
    .sort({ _id: 1 })
    .limit(40)
    .toArray();

  const jobs = data.map((job) => {
    const company = JSON.parse(JSON.stringify(job.company));
    const impact = JSON.parse(JSON.stringify(job.impact));
    const date = JSON.parse(JSON.stringify(job.date));
    const role = JSON.parse(JSON.stringify(job.role));
    const location = JSON.parse(JSON.stringify(job.location));
    const category = JSON.parse(JSON.stringify(job.category));
    const link = JSON.parse(JSON.stringify(job.link));

    return;

    {
      company: company;
      impact: impact;
      date: date;
      role: role;
      location: location;
      category: category;
      link: link;
    }
  });

  return {
    props: { jobs },
  };
}

I have tried stringifying all fields but have become stuck. Is there anyone that could give me some pointers?

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
user2095430
  • 83
  • 1
  • 8
  • As the error suggests, some fields are `undefined`. You either need to remove those or set them to `null` when you parse the data from the database. – juliomalves Jan 09 '21 at 15:51
  • 1
    I resolved this with this : https://stackoverflow.com/questions/61188494/getserversideprops-and-mysql-rowdatapacket – user2095430 Jan 09 '21 at 15:52

1 Answers1

0

Had the same issue, check what I've done to resolve it. Might be helpful. The serializing issue for me was the ObjectID in _id (like in your screenshot) and I'm just calling toString() for this _id =>

export async function getStaticProps () {

  let result;

  try {
    result = await fetchingPosts();
  }
  catch (err) {
    console.log('Error fetching data from MongoDB', err);
  }

  return {
    props: {
      data: result.map(item => {
        return {
          id: item._id.toString(),
          title: item.title,
          excerpt: item.excerpt,
          image: item.headerImgUrl,
          content: item.content,
        }
      })
    }
  }
}
Ivo Tsochev
  • 706
  • 5
  • 10