Return Custom Object as JSON

I am facing issues returning an object from MongoDB Atlas to be retrieved as JSON. Here is the structure of my code:

const result = collection.find().toArray();

const formatResult = {};

result.forEach((values) => {
   // I loop through the result and create an object
   const valuesData = {};

   Object.entries(values).forEach(([key, value]) => {
     valuesData[String(key)] = value;
   });

   // I add custom inside the array what I want
   //...
   formatResult[type][name]['things'] = data;
});

// Form A: Returns a plain text structure
// return JSON.stringify(formatResult, null, 2);

// Form B: Returns an object, but I get a processing error - {"error": "error processing request","error_code": "InternalServerError","link": "https://realm.mongodb.com/groups/...."}
// return formatResult;

Is there a way to return this in JSON format?

I’m looking for a way to return the formatResult variable in JSON format without getting the processing error. Any help or suggestions will be appreciated.

Note: Collection is a cursor type.
" Returns: A cursor to the documents that match the query criteria. When the find() method “returns documents,” the method is actually returning a cursor to the documents."
db.collection.find() — MongoDB Manual

For some reason that I don’t know (this doesn’t happen in Laravel) when you make a return with:

  • Obj : “error”: “error processing request”,“error_code”: “InternalServerError”
  • JSON.stringify(formatResult, null, 2) : returns a string instead of json.

In this case I convert that string to JSON by parsing the string.
return JSON.parse(JSON.stringify(finalResult)) : convert/parse the string to JSON

I don’t know how it works or what the “return” expression returns for the request. But that helped.

Solution

return JSON.parse(JSON.stringify(formatResult));

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.