Search code examples
arraysmongodbgoslicemongo-go

cannot decode array into an ObjectID


I have this struct and when I decode it from the database to struct I'm getting this error cannot decode array into an ObjectID

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

I'm using this function to decode

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
}

Here is a screenshot from the MongoDB


Solution

  • hitches in your database isn't a "simple" array, it's an array of arrays, so you may decode that into a value of type [][]primitive.ObjectID:

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

    Although each element in hitches contains a single element, so this "2D" array structure doesn't really make sense, it may be an error on the part where you create these documents. If you change (correct) that to create a "1-dimensional" array in MongoDB, then you may decode that into a value of type []primitive.ObjectID.