Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!