登录
首页 >  Golang >  Go问答

无法将 BSON 文档转换为对象

来源:stackoverflow

时间:2024-03-02 21:54:25 425浏览 收藏

本篇文章向大家介绍《无法将 BSON 文档转换为对象》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我在将 mongodb 集合中的 bson 文档解码为 go 中的 recipe 模型结构时遇到困难。

我能够很好地连接到我的数据库,并且我知道我的 cursor 正在迭代集合中的文档 - 如果我打印光标的值,我会得到一个 bson 文档,其中包含我知道的数据库中的信息。但是当我尝试将 cursor 解码为值 recipe 时,我得到一个 0 数组。

我尝试解码配方和配方指针,但得到相同的结果。

我已附加了我的 recipe 模型 (recipe.go) 以及处理数据库交互的存储库 (repository.go) 的代码:

食谱.go

type recipe struct {
    id      primitive.objectid `bson:"_id,omitempty" json:"_id,omitempty"`
    name    string             `bson:"name,omitempty" json:"name,omitempty"`
    creator string             `bson:"creator,omitempty" json:"creator,omitempty"`
    year    int32              `bson:"year,omitempty" json:"year,omitempty"`
}

repository.go

// get all recipes
func (r *recipesrepository) findall() ([]*models.recipe, error) {
    var recipes []*models.recipe

    findoptions := options.find()
    findoptions.setlimit(100)

    ctx, _ := context.withtimeout(context.background(), 15*time.second)

    cursor, err := collection.find(ctx, bson.d{{}}, findoptions)
    if err != nil {
        log.fatal(err)
    }

    defer cursor.close(ctx)
    for cursor.next(ctx) {
        var recipe models.recipe
        err := cursor.decode(&recipe)
        if err != nil {
            log.fatal(err)
        }
        recipes = append(recipes, &recipe)
    }
    if err := cursor.err(); err != nil {
        log.fatal(err)
    }
    return recipes, err
}

以下是在每次迭代中打印 cursor 和解码的光标 recipe 时得到的示例:

// log.Println(cursor)

&{{"_id": {"$oid":"5fc98f23df7de068187c78a1"},"name": "Fake name","creator": "Fake Creator","year": {"$numberInt":"2020"}} 0xc0007b4160 0xc0004ff200 0 0xc00014ec40 0xc0003a23c0 }

// log.Println(recipe)

{[0 0 0 0 0 0 0 0 0 0 0 0]   0}

// log.Println(&recipe)

&{[0 0 0 0 0 0 0 0 0 0 0 0]   0}

任何指导将不胜感激。谢谢!


解决方案


Burak Serdar 在评论中回答了这个问题:

好了,本文到此结束,带大家了解了《无法将 BSON 文档转换为对象》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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