登录
首页 >  Golang >  Go问答

Mongo-go-driver 中的解析存在问题

来源:stackoverflow

时间:2024-02-19 14:09:23 186浏览 收藏

本篇文章给大家分享《Mongo-go-driver 中的解析存在问题》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

例如,我有这样的结构:

type overview struct {
    symbol               string             `json:"symbol,omitempty"`
    assettype            string             `json:"assettype,omitempty"`
    name                 string             `json:"name,omitempty"`
    description          string             `json:"description,omitempty"`
    ...
    ...
}

除此之外,我还有其他几个结构。 我的函数为 decode() 选择合适的结构,但是当我尝试从数据库获取数据时,我得到以下形式的结果:

[
    {
        "key": "_id",
        "value": "618aa6f2a64cb8105a9c7984"
    },
    {
        "key": "symbol",
        "value": "ibm"
    },
    {
        "key": "fiscalyearend",
        "value": "december"
    },
    ...
    ...
]

我期望以我的结构形式得到响应,但我得到了这样一个数组。我尝试自己声明响应的结构:var result models.overview。之后,问题就消失了,但这不是我的问题的解决方案

这是我的功能:

var (
    models map[string]interface{}
)

func init() {
    models = make(map[string]interface{})
    models["Overview"] = models.Overview{}
    models["Earnings"] = models.Earnings{}
    ...
    ...
}
func GetDbData(collection string, db *mongo.Database, filter bson.D) (interface{}, error) {
    var result = models[collection] // Choosing a structure
    res := db.Collection(collection).FindOne(context.TODO(), filter)
    err := res.Decode(&result)
    if err != nil {
        return nil, err
    }
    return result, nil
}

我不明白为什么会发生这种情况,我希望有人已经遇到过这个问题并且能够帮助我


正确答案


https://jira.mongodb.org/browse/GODRIVER-988

Another approach to solve this can be by first decoding it into bson.M type and then unmarshalling it to your struct. Yes, this is not optimal.

eg:

func GetMonthStatusByID(ctx context.Context, id string) (interface{}, error) {
 var monthStatus interface{}
 filter := bson.M\{"_id": id}
 err := db.Collection("Months").FindOne(ctx, filter).Decode(&monthStatus)
 return monthStatus, err
}
The above snippet should be changed to:

func GetMonthStatusByID(ctx context.Context, id string) (interface{}, error) {
 var monthStatus interface{}
 filter := bson.M\{"_id": id}
tempResult := bson.M{}
 err := db.Collection("Months").FindOne(ctx, filter).Decode(&tempResult)
if err == nil {   
    obj, _ := json.Marshal(tempResult)
    err= json.Unmarshal(obj, &monthStatus)
}
 return monthStatus, err
}

今天关于《Mongo-go-driver 中的解析存在问题》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>