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

118
Vistas
MongoDB - NodeJS - loosing ObjectId when serializing to JSON

Trying to write / export some data from MongoDB to a file, where later I'd like to read/update them back.

    filehandle = await fs.promises.open(params.credentialsFilename, 'w');
    // ... some other code
    let records= await mongoConn.db(params.db).collection(COLLECTION_RECORDS)
         .find({}).toArray();
    for(const anObj of records) {
        console.log('[exportMongoDbWriteToFile] writing _id: ', anObj._id);
        console.log(anObj);
        await filehandle.write(JSON.stringify(anObj, null, 2)); // start array
        // await filehandle.write(anObj); // doesn't work with an object
    }

Th problem is that JSON.stringify(anObj) converts the ObjectId(hex_id) to a string of hex_id for the _id property (for any property using the ObjectId reference).

This is a problem as reading the data back to the MongoDB the string hex_id is not/ is different than ObjectId(hex_id) (as far I know).

However console.log(anObj); actually writes the full JSON with the ObjectId notation, not sure how the object is serialized for the console, we'd like to have the same output written into the file too.

Edit: we're using the default mongodb library

over 4 years ago · Santiago Trujillo
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