如何获取Mongo文档并将它们作为JSON API响应返回

huangapple go评论148阅读模式
英文:

How to get Mongo documents and return them as a JSON API response

问题

我正在编写一个API,该API检索Mongo文档并将这些文档作为JSON响应返回。

我可以通过创建一个具有正确字段映射的结构体来实现这一点,但由于我不处理这些文档,我只想将从下面的代码中获取的原始数据转换为JSON。然后,我的API将返回JSON作为响应。

我有以下代码:

var raw []bson.Raw
err = myCollection.Find(
      bson.M{"name": name},
).All(&raw)

我想将raw转换为JSON。我该如何做?除了开始创建一个bson.Raw之外,还有其他更好的方法吗?

技术栈:
Go 1.1
mgo v1 http://godoc.org/labix.org/v1/mgo
bson v1 http://godoc.org/labix.org/v1/mgo/bson

谢谢。

英文:

I'm writing an API which retrieves Mongo documents and return those documents as a JSON response.

I can certainly do this by creating a struct with the proper field mappings, but since i'm not processing these documents, I simply want to convert the raw data I get from the code below to JSON. My API will then return the JSON as a response.

I have the following code:

var raw []bson.Raw
err = myCollection.Find(
      bson.M{"name": name},
).All(&raw)

I want to convert raw to JSON. How would I do that? Is there a better of this this other than by starting to create a bson.Raw?

Tech stack:
Go 1.1
mgo v1  http://godoc.org/labix.org/v1/mgo
bson v1 http://godoc.org/labix.org/v1/mgo/bson

Thanks.

答案1

得分: 1

将其解组为映射而不是结构体:

var maps []bson.M
err = myCollection.Find(bson.M{"name": name}).All(&maps)

这样,你可以将这些映射提供给encoding/json包的Marshal函数。

英文:

Unmarshal it into maps instead:

var maps []bson.M
err = myCollection.Find(bson.M{"name": name}).All(&maps)

This way you can provide these same maps to the encoding/json package's Marshal function.

huangapple
  • 本文由 发表于 2013年9月5日 01:16:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/18620016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定