【问题标题】:Go Firestore get all documents from collectionGo Firestore 从集合中获取所有文档
【发布时间】:2020-08-08 22:24:16
【问题描述】:

使用 go 和 firestore 创建网络应用。我遇到了一个奇怪的问题。 如果我使用 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 不起作用?

有没有更好的方法来从集合中提取所有文档,然后专门提取单个文档?

【问题讨论】:

    标签: go google-cloud-firestore


    【解决方案1】:

    仅当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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 2020-05-30
      • 1970-01-01
      • 2018-04-03
      相关资源
      最近更新 更多