duanmangxie7131 2019-01-16 20:34
浏览 141
已采纳

使用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)

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

I can easily convert last result into JSON without using any structs:

var jsonDoc bson.M
err = bson.Unmarshal(doc, &jsonDoc)
return jsonDoc

I can't convert docs into JSON and use as a result in my Rest server.

Update 2019-01-17:

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

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}, ...].

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 and mongodb equivalent:

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);
            }
        });
});
  • 写回答

1条回答 默认 最新

  • duan32342 2019-01-17 19:22
    关注

    This code works. After few hours of trying and thanks to good luck I managed to solve this issue. Maybe someone will explain this?

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#vscode#的问题:布料滤波算法中C++实现pcl在Vscode中pcl库没有#include <pcl>
  • ¥15 fpga:ov5640采集tft显示
  • ¥20 创建taro项目,在vscode上能够写跨平台写微信小程序代码
  • ¥15 网站出现错误跳转问题
  • ¥15 Docker容器里已经安装了ssh,但打包迁移到新机器一直容器一直提示unrecognized service。
  • ¥15 综合布线实例设计,就好看好看不恐怖可好滤镜好聚
  • ¥15 使用moviepy库视频合并时出错
  • ¥30 FLUENT液固传质UDF
  • ¥15 怎么看梯度直方图以,怎么判断梯度消失/爆炸,怎么解决
  • ¥15 aspnetdll文件访问拒绝