【问题标题】:cannot decode array into an ObjectID无法将数组解码为 ObjectID
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 是的!我明白你在说什么!谢谢!我改变了我的数据结构! :D
猜你喜欢
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 2021-08-25
  • 1970-01-01
相关资源
最近更新 更多