Suppress value types in MongoDB Stitch function

雨燕双飞 提交于 2020-12-15 17:44:40

问题


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;
};

回答1:


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.



来源:https://stackoverflow.com/questions/55306499/suppress-value-types-in-mongodb-stitch-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!