Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda