LoginSignup
0
0

More than 3 years have passed since last update.

Go: Cloud Firestore のデータを読む (Read)

Posted at
firestore_read.go
// ---------------------------------------------------------------
//  firestore_read.go
//
//                  Dec/16/2020
//
// ---------------------------------------------------------------
package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "strconv"

    firebase "firebase.google.com/go"
    "google.golang.org/api/iterator"
    "google.golang.org/api/option"
)

// ---------------------------------------------------------------
func main() {
    fmt.Fprintf (os.Stderr,"*** 開始 ***\n")
    // 初期化
    ctx := context.Background()
    sa := option.WithCredentialsFile("./application_default_credentials.json")
    app, err := firebase.NewApp(ctx, nil, sa)
    if err != nil {
        log.Fatalln(err)
    }

    client, err := app.Firestore(ctx)
    if err != nil {
        log.Fatalln(err)
    }

    // データ読み取り
    iter := client.Collection("cities").Documents(ctx)
    for {
        doc, err := iter.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            log.Fatalf("Failed to iterate: %v", err)
        }
//      fmt.Println(doc.Ref.ID)
//      fmt.Println(doc.Data())
        fmt.Printf("%s\t",doc.Ref.ID)
        fmt.Printf("%s\t",doc.Data()["name"])
        population := doc.Data()["population"].(int64)
        str_population := strconv.FormatInt(population,10)
        fmt.Printf("%s\t",str_population)
        fmt.Println(doc.Data()["date_mod"])
    }

    // 切断
    defer client.Close()

    fmt.Fprintf (os.Stderr,"*** 終了 ***\n")
}

// ---------------------------------------------------------------

実行コマンド

```bash
project_id="project-dec16-2020"
echo $project_id
export GOOGLE_CLOUD_PROJECT=$project_id
#
go run firestore_read.go
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0