Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 695
OhhhThatVarun Avatar asked Apr 13 '26 05:04

OhhhThatVarun


1 Answers

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.

like image 110
icza Avatar answered Apr 15 '26 00:04

icza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!