将数据附加到使用'reflect'指向定义的结构的接口上]]

问题描述 投票:0回答:1

我正在尝试创建一个函数,以使其从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集合中获取所有文档,并将它们查询为声明的结构。为此,我为接口类型的功能设置参数...

mongodb go struct reflection append
1个回答
0
投票

问题中的代码将结构docs传递给需要切片的函数。在docs中传递切片字段的地址,而不是docs本身。

© www.soinside.com 2019 - 2024. All rights reserved.