1 回答
TA贡献1757条经验 获得超7个赞
以下代码可以运行:
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
}
- 1 回答
- 0 关注
- 109 浏览
添加回答
举报