使用mongo-go-driver将结果转换为不带结构的JSON [英] convert result into JSON without structs using mongo-go-driver
问题描述
在将结果转换为JSON之前,我不想使用结构.假设我有一些结果:
I don't want to use structs before converting results into JSON. Let's say I have some results:
result, err := collection.Find(ctx, filter, options)
我可以在 docs 变量中收集所有结果,而在 doc 变量中收集最后的结果:
I can collect all results in docs variable and last result in doc variable:
var doc bson.Raw
var docs []bson.Raw
for result.Next(ctx) {
document, err := result.DecodeBytes()
if err != nil {
log.Println(err)
}
doc = document
docs = append(docs, doc)
}
我可以轻松地将最后的结果转换为JSON,而无需使用任何结构:
I can easily convert last result into JSON without using any structs:
var jsonDoc bson.M
err = bson.Unmarshal(doc, &jsonDoc)
return jsonDoc
我无法将文档转换为JSON并不能在我的Rest服务器中使用.
I can't convert docs into JSON and use as a result in my Rest server.
更新2019-01-17:
我在REST服务器中使用结果是这样的:
I'm using result in my REST server like this:
user.GET("/booking/customer/:id", func(c *gin.Context) {
result := GetAllCustomerBookings(c.Param("id"))
c.JSON(http.StatusOK, result)
})
,所以它不能循环遍历值. 问题:如何将[] bson.Raw转换为[] byte或bson.Raw. 想象一下,现在我在数组的每个值中都有{JSON}.我需要这样的JSON:[{JSON},{JSON},...].
so it can't be a loop through values. The question: how to convert []bson.Raw to []byte or bson.Raw. Let's imagine that now I have {JSON} in each value of array. I need one JSON like this: [{JSON}, {JSON}, ...].
使用nodejs更容易,因为我可以在一个JSON文档中发送所有记录. Go和mongodb-go-driver需要遍历所有记录,而我不知道如何构建一个JSON文档.
Using nodejs was easier because I could send all records in one JSON document. Go and mongodb-go-driver needs to go through all records and I don't know how to build one JSON document.
Nodejs和mongodb等效项:
router.get('/bookings/customer/:id', function (req, res, next) {
db.Bookings.find({
"booking.customer._id": {
$eq: req.params.id
}
}).sort({
"booking.arrival_date": -1
},
function (err, bookings) {
if (err) {
res.send(err);
} else {
res.json(bookings);
}
});
});
推荐答案
此代码有效.经过数小时的尝试,并祝您好运,我设法解决了这个问题.也许有人会解释这个?
This code works. After few hours of trying and thanks to good luck I managed to solve this issue. Maybe someone will explain this?
我使用 bson.M 和 result.Decode()代替 bson.Raw ,而不是 result.DecodeBytes() 现在,我得到的输出与nodejs给我的输出相同.
Instead of bson.Raw I used bson.M and result.Decode() instead of result.DecodeBytes() Now I have the same output as nodejs gives me.
var docs []bson.M
for result.Next(ctx) {
var document bson.M
err = result.Decode(&document)
if err != nil {
log.Println(err)
}
docs = append(docs, document)
}
return docs
这篇关于使用mongo-go-driver将结果转换为不带结构的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!