0

This is a GoLang, Firebase AdminSDK question.

This example works to iterate through all of the documents in a FireStore DB.

How can I get the Document Name?

To put another way: If the collection name is JohnyCollection, and JohnyCollection has 20 Documents called (Document1, Document2.... Document20), how do I get the document name in golang Code?

//========================================

package main
import (
    "context"
    "fmt"
    "log"
    "firebase.google.com/go"
    "google.golang.org/api/iterator"
    "google.golang.org/api/option"
)
func check(e error) {
    if e != nil {
        panic(e)
    }
}
func main() {
    ctx := context.Background()
    sa := option.WithCredentialsFile("./scai-qit-fb-adminsdk.json")
    app, err := firebase.NewApp(ctx, nil, sa)
    if err != nil {
        log.Fatalf("error initializing app: %v\n", err)
    }
    client, err := app.Firestore(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()
    iter := client.Collection("COMPLEX_NONACS").Documents(ctx)
    for {
        doc, err := iter.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            log.Fatalf("Failed to iterate: %v", err)
        }
        //This part works.  WIll return a Map of each Document
        fmt.Println("--------------------------/n")
        fmt.Println(doc.Data())

        //  This is the question.  How do I get the INDEX name of the Document?
        //  something like...
        fmt.Println(doc.Index_value_or_something_that_returns_IndexName())

        //  for example...
        // {
        // "ABC":{"line1":"yabba dabba","line2":"dingo dong"},
        // "DEF":{"line1":"hooty tooty","line2":"blah blah"}
        // }
        // How to just get the "ABC"  and "DEF"

    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
IrishGringo
  • 3,864
  • 7
  • 37
  • 49

1 Answers1

1

You can get the document ID from the DocumentSnapshot, by first looking up the DocumentRef:

 fmt.Println(doc.Ref.ID)

See the reference docs for DocumentSnapshot and DocumentRef.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807