英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论