登录
首页 >  Golang >  Go问答

无法将数组解码为 ObjectID

来源:stackoverflow

时间:2024-03-29 21:21:33 161浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《无法将数组解码为 ObjectID》,涉及到,有需要的可以收藏一下

问题内容

我有这个结构,当我将其从数据库解码为结构时,我收到此错误 cannot 将数组解码为 objectid

type student struct {
    id           primitive.objectid   `bson:"_id,omitempty"`
    ...
    hitches      []primitive.objectid `bson:"hitches"`
    ...
}

我正在使用这个函数来解码

func GetStudentByID(ID primitive.ObjectID) model.Student {

    // Filter
    filter := bson.M{"_id": ID}

    // Get the collection
    studentCollection := GetStudentCollection()

    // The object that it will return
    student := model.Student{}

    // Search the database
    err := studentCollection.FindOne(context.TODO(), filter).Decode(&student)

    if err != nil {
        fmt.Println("Student DAO ", err)  <----------- Error is output here
        return model.Student{}
    }

    return student
}

这是 mongodb 的屏幕截图


解决方案


数据库中的 hitches 不是一个“简单”数组,而是一个数组数组,因此您可以将其解码为 [][]primitive.objectid 类型的值:

type Student struct {
    ID      primitive.ObjectID     `bson:"_id,omitempty"`
    ...
    Hitches [][]primitive.ObjectID `bson:"hitches"`
    ...
}

尽管 hitches 中的每个元素都包含单个元素,因此这种“2d”数组结构实际上没有意义,但它可能是您创建这些文档的部分出现错误。如果您更改(更正)它以在 mongodb 中创建“一维”数组,那么您可以将其解码为 []primitive.objectid 类型的值。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《无法将数组解码为 ObjectID》文章吧,也可关注golang学习网公众号了解相关技术文章。

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