Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
`object` ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types

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))

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

or As Chris mentioned you can use .lean() method.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda