3

我有这个结构,当我将它从数据库解码为结构时,我收到了这个错误cannot decode array into an 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的截图

4

1 回答 1

4

hitches在您的数据库中不是“简单”数组,而是数组数组,因此您可以将其解码为 type 的值[][]primitive.ObjectID

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

尽管其中的每个元素都hitches包含一个元素,因此这种“2D”数组结构并没有真正的意义,它可能是您创建这些文档的部分的错误。如果您更改(更正)它以在 MongoDB 中创建“一维”数组,那么您可以将其解码为 type 的值[]primitive.ObjectID

于 2019-09-30T08:51:05.620 回答