猿问

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

使用 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 不起作用?


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


SMILET
浏览 124回答 1
1回答

喵喔喔

doc.DataTo(&b)该程序仅在返回错误时将博客附加到结果中。编写如下代码:var bs models.Blogsiter := client.Collection("blogs").Documents(ctx)defer iter.Stop() // add this line to ensure resources cleaned upfor {    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)}
随时随地看视频慕课网APP

相关分类

Go
我要回答