为了账号安全,请及时绑定邮箱和手机立即绑定

Go Firestore 从集合中获取所有文档

Go Firestore 从集合中获取所有文档

Go
SMILET 2022-06-01 11:37:54
使用 go 和 firestore 创建 Web 应用程序。我遇到了一个奇怪的问题。如果我使用 NewDoc 方法保存数据    ref := client.Collection("blogs").NewDoc()    _, err := ref.Set(ctx, mapBlog)    if err != nil {        // Handle any errors in an appropriate way, such as returning them.        log.Printf("An error has occurred: %s", err)    }我有能力使用    var bs models.Blogs    iter := client.Collection("blogs").Documents(ctx)    for {        var b models.Blog        doc, err := iter.Next()        if err != nil {            fmt.Println(err)        }        if err == iterator.Done {            break        }        if err := doc.DataTo(&b); err != nil {            fmt.Println(doc.Data())            bs = append(bs, b)        }    }现在,当我只想查找博客集合中的所有文档时,这非常棒。但是后来我遇到了无法从博客集合中查询特定博客的问题。我通过查看文档并保存这样的帖子解决了这个问题。//p is a struct and p.ID is just a string identifier// the docs show creating a struct with an ID and then an embedded struct within. _, err := client.Collection("blogs").Doc(p.ID).Set(ctx, p)     if err != nil {        fmt.Println(err)    }但是由于我自己创建了 docID,因此我使用从整个集合中检索所有文档 if err := doc.DataTo(&b); err != nil {            fmt.Println(doc.Data())            bs = append(bs, b)            fmt.Println(b)        }不再工作。基本上我需要能够为一页加载所有博客,然后如果单击特定博客,我需要能够获取 ID 并仅查找集合中的一个文档。如果我自己设置文档 ID,为什么 doc.DataTo 不起作用?有没有更好的方法来通常只从集合中提取所有文档,然后专门提取单个文档?
查看完整描述

1 回答

?
喵喔喔

TA贡献1735条经验 获得超5个赞

doc.DataTo(&b)该程序仅在返回错误时将博客附加到结果中。


编写如下代码:


var bs models.Blogs

iter := client.Collection("blogs").Documents(ctx)

defer iter.Stop() // add this line to ensure resources cleaned up

for {

    doc, err := iter.Next()

    if err == iterator.Done {

        break

    }

    if err != nil {

        // Handle error, possibly by returning the error

        // to the caller. Break the loop or return.

        ... add code here

    }

    var b models.Blog

    if err := doc.DataTo(&b); err != nil {

        // Handle error, possibly by returning the error 

        // to the caller. Continue the loop, 

        // break the loop or return.

        ... add code here

    }

    bs = append(bs, b)

}


查看完整回答
反对 回复 2022-06-01
  • 1 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号