I am trying to create a function where it gets all the documents from a Mongo Collection and queries them to declared structs.To achieve this I set the parameters for the function of type interface so it can work with two structs. Here is my code:
//struct doc = document from Mongo Collection
//struct docs = []doc each element is a document
createQuery(&doc, &docs, collection)
func createQuery(doc interface{}, docs interface{}, c *mongo.Collection) {
documents := reflect.ValueOf(docs).Elem()
document := reflect.ValueOf(doc)
cur, err := c.Find(context.Background(), bson.D)
if err != nil {
log.Fatal(err)
}
for cur.Next(context.Background()) {
err = cur.Decode(document.Interface())
if err != nil {
log.Fatal(err)
}
documents.Set(reflect.Append(documents, document))
fmt.Println(doc)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
if err != nil {
fmt.Printf("oh shit this is the error %s \n", err)
}
cur.Close(context.Background())
fmt.Printf("documents: %+v\n", documents.Interface())
fmt.Printf("document: %+v\n", document.CanSet())
}
panic: reflect: call of reflect.Append on struct Value
I was able to set data to doc using the document variable, although, when doing document.CanSet() it is false (so it may not even work). Where the program breaks is when I try to append the document to the documents interface.
Aucun commentaire:
Enregistrer un commentaire