Reputation: 3
Can't figure out how to modify a struct type variable passed as pointer to a function that takes in an empty interface
I am creating a kind of library that works with MongoDB database through official go driver. I am passing a struct pointer which then gets filled with data from database (MongoDB cursor.Decode
). This works fine for a single document, but when I try to return an array of documents, only the parent documents are correct, but children(embedded) stay same for all the elements in array (probably store reference and not the actual value).
Actual code:
// passing model pointer to search function
result, _ := mongodb.Search(&store.Time{},
mongodb.D{mongodb.E("transdate",
mongodb.D{mongodb.E("$gte", timeSearch.DateFrom), mongodb.E("$lte", timeSearch.DateTo)})})
...
func Search(model interface{}, filter interface{}) (result ModelCollection, err error) {
collection := Database.Collection(resolveCollectionName(model))
var cursor *mongo.Cursor
cursor, err = collection.Find(Context, filter)
if err != nil {
log.Fatal(err)
}
for cursor.Next(Context) {
if err := cursor.Decode(model); err != nil {
log.Fatal(err)
}
modelDeref := reflect.ValueOf(model).Elem().Interface()
result = append(result, modelDeref)
}
return
}
Here is the closest playground example I could come up with. I replaced MongoDB cursor.Decode()
with my own Decoding function, but this doesn't even update parent properties. Children stay same though
https://play.golang.org/p/lswJJY0yl80
Expected:
result:[{A:1 Children:[{B:11}]} {A:2 Children:[{B:22}]}]
Actual:
result:[{A:init Children:[{B:22}]} {A:init Children:[{B:22}]}]
Upvotes: 0
Views: 802
Reputation: 38223
You're decoding into the same pointer, so you'll always end up with a slice containing elements whose value is the same as the one you decoded last.
You should instead, on each iteration, initialize a new instance of the model's type and then decode into that.
result, _ := mongodb.Search(store.Time{}, ...) // pass in non-pointer type to make life easier
// ...
func Search(model interface{}, filter interface{}) (result ModelCollection, err error) {
collection := Database.Collection(resolveCollectionName(model))
var cursor *mongo.Cursor
cursor, err = collection.Find(Context, filter)
if err != nil {
log.Fatal(err)
}
for cursor.Next(Context) {
v := reflect.New(reflect.TypeOf(model)).Interface() // get a new pointer instance
if err := cursor.Decode(v); err != nil { // decode
log.Fatal(err)
}
md := reflect.ValueOf(v).Elem().Interface()
result = append(result, md) // append non-pointer value
}
return
}
Upvotes: 1