Deliri
Deliri

Reputation: 126

Go Firestore get all documents from collection

Creating a web app using go and firestore. I'm running into a weird problem. If I save the data using the NewDoc method

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

I have the ability to retrieve the entire collection using the

    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)

        }
    }

Now, this is great when I just want to look up all the documents in the blogs collection. But then I run into the problem of not being able to query a specific blog from the blogs collection. I solved that problem by looking at the documentation and saving posts like this.

//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)
    }

But since I'm creating the docID myself, my retrieval of all documents from the entire collection using

 if err := doc.DataTo(&b); err != nil {
            fmt.Println(doc.Data())
            bs = append(bs, b)
            fmt.Println(b)
        }

no longer works. Basically I need to be able to load all blogs for one page, then if a particular blog is clicked on, I need to be able to grab the ID and go look up just one document in the collection. Why doesn't the doc.DataTo not work if I set the Doc ID myself?

Is there a better way to generally just pull up all documents out of a collection and then specifically pull up a single document?

Upvotes: 1

Views: 3454

Answers (1)

Thundercat
Thundercat

Reputation: 121159

The program appends blogs to the result only when doc.DataTo(&b) returns an error.

Write the code like this:

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

Upvotes: 6

Related Questions