我正在尝试读取给定 Firestore 集合下的所有文档,并将文档作为结构数组返回。函数内的日志将数据输出为 Firestore 文档,但函数外的 struct 数组始终为空数组。
读取集合下所有文档的功能。
func (fc *FirebaseClient) ReadCollection(collectionPath string, objects interface{}) error {
ctx := context.Background()
opt := option.WithCredentialsJSON([]byte(os.Getenv("FIREBASE_CREDENTIALS")))
client, err := firestore.NewClient(ctx, os.Getenv("FIREBASE_PROJECT_ID"), opt)
if err != nil {
return err
}
defer client.Close()
collectionRef := client.Collection(collectionPath)
docs, err := collectionRef.DocumentRefs(ctx).GetAll()
if err != nil {
return err
}
log.Printf("Total documents: %i", len(docs))
objs := make([]interface{}, len(docs))
for i, doc := range docs {
docsnap, err := doc.Get(ctx)
if err != nil {
return err
}
if err := docsnap.DataTo(&objs[i]); err != nil {
return err
}
log.Printf("obj: %v", objs[i])
}
objects = objs
log.Printf("objects: %v", objects)
return nil
}
调用函数的代码
var ss []SomeStruct
fc := new(insightech.FirebaseClient)
if err := fc.ReadCollection("mycollection", ss); err != nil {
return
}
ss
总是一个空数组。我不想指定结构类型的原因是使 ReadCollection 函数具有通用性,因此我可以调用它来读取不同的集合。
该代码不会触发任何错误,但结果是一个空数组,即使
objects
interface 绝对是一个包含元素的数组。
最佳答案
感谢@mkopriva,以下代码有效:
func (fc *FirebaseClient) ReadCollection(collectionPath string, objects interface{}) error {
ctx := context.Background()
opt := option.WithCredentialsJSON([]byte(os.Getenv("FIREBASE_CREDENTIALS")))
client, err := firestore.NewClient(ctx, os.Getenv("FIREBASE_PROJECT_ID"), opt)
if err != nil {
return err
}
defer client.Close()
collectionRef := client.Collection(collectionPath)
docs, err := collectionRef.DocumentRefs(ctx).GetAll()
if err != nil {
return err
}
log.Printf("Total documents: %i", len(docs))
dest := reflect.ValueOf(objects).Elem()
log.Printf("dest: %v", dest)
for _, doc := range docs {
docsnap, err := doc.Get(ctx)
if err != nil {
return err
}
obj := reflect.New(dest.Type().Elem())
if err := docsnap.DataTo(obj.Interface()); err != nil {
return err
}
log.Printf("obj: %v", obj)
dest = reflect.Append(dest, obj.Elem())
}
reflect.ValueOf(objects).Elem().Set(dest)
log.Printf("objects: %v", dest)
return nil
}
var ss []SomeStruct
fc := new(insightech.FirebaseClient)
if err := fc.ReadCollection("mycollection", &ss); err != nil {
return
}
关于arrays - 如何通过引用将结构数组作为接口(interface)传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58726751/