go - 前往Firestore获取收藏中的所有文档

标签 go google-cloud-firestore

使用go and 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)

        }
    }

现在,当我只想查找Blog集合中的所有文档时,这很棒。
但是后来我遇到了一个问题,即无法从博客集中查询特定博客。我通过查看文档并保存这样的帖子解决了该问题。
//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并仅查找集合中的一个文档。如果我自己设置Doc ID,为什么doc.DataTo不起作用?

是否有更好的方法通常只从集合中拉出所有文档,然后专门拉出单个文档?

最佳答案

该程序仅在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)
}

关于go - 前往Firestore获取收藏中的所有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61423735/

相关文章:

go - 如何关闭定时器 channel ?

不同包的Golang函数泛化

vue.js - Firestore : "There was an unknown error while processing the request"

firebase - 如何向数据库中的所有当前文档添加新字段?

firebase - Firestore 批量写入与事务

mysql - 意外的类型,期望的名称

http - 在Golang中为http请求指定网络接口(interface)

golang 返回的参数太多

java - Maven 中的 FirebaseApp

android - 如何通过类中的方法通过 FirebaseFirestore 查询检索数据列表?