本文介绍了抑制 MongoDB Stitch 函数中的值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stitch 函数 返回每个非字符串字段的值类型.我相信这是因为函数在 MongoDB 扩展 JSON 中返回数据.

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

另一方面,Mongo Shell 返回标准 JSON,没有值类型.

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

如何抑制 MongoDB 函数返回的值类型?是否可以将 EJSON 转换回 JSON?

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

例如,对于日期字段,Mongo Shell 返回:

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

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

Stitch 函数中的相同查询返回:

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

推荐答案

当一个 Function 结果传递给客户端时,它确实被序列化为 EJSON.

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

理想情况下,您的客户端可以将 EJSON 解析回常规的 JS 对象,例如使用 EJSON 库,该库也内置在 Stitch SDK.

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.

当然,如果你使用的是 Stitch SDK,调用函数直接甚至更好.

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

另一种选择是使用 响应对象 传递 JSON,如下所示:

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

请注意,JSON 不能表示某些特殊的 BSON 类型,例如对象 ID,因此您在决定要返回哪些数据时需要牢记这一点.

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.

这篇关于抑制 MongoDB Stitch 函数中的值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:26