我正在尝试创建一个函数,以使其从Mongo集合中获取所有文档,并将它们查询为声明的结构。为此,我为类型接口的功能设置了参数,以便可以使用两个结构。这是我的代码:
var docs entities.Projects //type struct Title... Position... var doc entities.Project //type struct Projects []Project //doc represents a document from Mongo Collection //docs represents an array of documents, each element is a document //collection has type *mongo.Collection and points to the desired collection on MongoDB. 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) } //Error is thrown here 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()) } ---ERROR OUTPUT--- panic: reflect: call of reflect.Append on struct Value
我能够使用document变量将数据设置为doc,尽管当document.CanSet()为false时(所以它甚至可能无法工作)。当我尝试将文档附加到文档界面时,程序中断了。
我正在尝试创建一个函数,以使其从Mongo集合中获取所有文档,并将它们查询为声明的结构。为此,我为接口类型的功能设置参数...
问题中的代码将结构docs
传递给需要切片的函数。在docs
中传递切片字段的地址,而不是docs
本身。