登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-30 14:54:30 355浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《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 不起作用?

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


解决方案


仅当 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 从集合中获取所有文档》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>