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