Search code examples
mongodbmongodb-stitch

Suppress value types in MongoDB Stitch function


A Stitch function returns value types for each non-string field. I believe this is because functions return data in MongoDB Extended JSON.

The Mongo Shell, on the other hand, returns standard JSON, and no value types.

How do I suppress value types returned by a MongoDB function? Is it possible to convert EJSON back to JSON?

For a date field, for example, the Mongo Shell returns:

"dob" : ISODate("1995-01-11T00:00:00.000-07:00")

The same query in a Stitch function returns:

"dob": {
  "$date": {
    "$numberLong": "232182000000"
  }

My Stitch function looks like this:

exports = function(){
    const collection = context.services.get("mongodb-atlas").db("mydb").collection("mycollection");
    const doc = collection.find().toArray();
  return doc;
};

Is there a helper function that can strip out the value types? Something like...

exports = function(){
    const collection = context.services.get("mongodb-atlas").db("mydb").collection("mycollection");
    const doc = collection.find().toArray();
    const noValueTypes = doc.stripValueTypes()
  return noValueTypes;
};

Solution

  • When a Function result is passed to the client, it is indeed serialized as EJSON.

    Ideally, your client can parse EJSON back into regular JS objects, e.g. with the EJSON library, which is also built into the Stitch SDK.

    Of course, if you are using the Stitch SDK, calling the function directly is even better.

    Another option is to use the response object to pass JSON, like so:

    exports = function(request, response) {
      // ... get data ...
      response.addHeader(
        "Content-Type",
        "application/json"
      );
      response.setBody(JSON.stringify(myData));
    };
    

    Note that JSON can't represent some special BSON types, such as object id, so you will want to keep this in mind when deciding what data to return.