【发布时间】:2019-09-30 08:43:40
【问题描述】:
我有这个结构,当我将它从数据库解码为结构时,我收到了这个错误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 的屏幕截图
【问题讨论】:
-
hitches在您的数据库中是一个数组数组,因此您可以将其解码为[][]primitive.ObjectID类型的值。 -
可能值得注意的是,由于每个“数组数组”只有一个成员,这可能是插入数据时的错误。您可能应该考虑纠正它,而不是“围绕它进行编码”。
-
@NeilLunn 是的,我明白你在说什么。
标签: arrays mongodb go slice mongo-go