Home > Back-end >  `object` ("[object Object]") cannot be serialized as JSON. Please only return JSON seriali
`object` ("[object Object]") cannot be serialized as JSON. Please only return JSON seriali

Time:05-10

I am using NextJS and I previously called an internal /api route to get this data using fetch(), however, I realized that for production, it won't let you use internal api calls inside getServerSideProps Therefore, I am trying to call my MongoDB database directly from getServerSideProps.

My problem is that I get the error that my posts data that I am passing as props isn't serializable: "object ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types."

I don't understand why, as it is in the form of: [object Object],[object Object],[object Object], etc. which should work when it's passed?

My code is below for reference (explanations below the code):

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,
        }
    }
}

My data I receive from my database is roughly as follows: [{"title":"1","body":"1","id":"6276767ca21167f5043d3dc8"},{"title":"2","body":"2","id":"6276767fa21167f5043d3dc9"},{"title":"3","body":"3","id":"62767682a21167f5043d3dca"}, etc.] Doesn't this match the format of my posts I'm passing as props?

The line console.log("RESULT: " result) prints: [object Object],[object Object],[object Object],[object Object], etc.

ANSWER from @jabaa: change the return to this line: startingPosts: JSON.parse(JSON.stringify(posts))

CodePudding user response:

return {
        props: {
            startingID: String(returnID),
            startingError: error,
            startingPosts: JSON.parse(JSON.stringify(posts)),
        }
    }

  • Related