The map decoder attempts to set the key of a map value as a string. When the key type is instead a non-primitive string type, e.g. type mystring string, the map decoder panics because it does not first convert the string value of the BSON to the appropriate type. To fix this, convert the BSON key string to the map's key type before setting.
(original description below)
I've a function that finds an item on the database, but I get a reflection error when trying to decode it.
This is the error I get:
reflect.Value.SetMapIndex: value of type string is not assignable to type models.DataType
And here you have the code I use to find the element on the database:
//Find finds a device func (r *Device) Find(manufacturer string, model string, sn string) (d *models.Device) { var dev models.Device ctx, cancel := context.WithTimeout(context.Background(), db.Timeout*time.Second) defer cancel() err := r.col.FindOne(ctx, bson.M{ "manufacturer": manufacturer, "model": model, "serialNumber": sn, "active": true, }).Decode(&dev) if err != nil { log.Fatal(err) d = nil } d = &dev return }
I attach the two models related to the problem, the device has a map where the map index is not a string but a custom type defined as string.
I was using mgo driver without any problems before, but after migration to this official driver when I try to run my code I get a runtime exception.