LoginSignup
0
0

More than 3 years have passed since last update.

Go: Cloud Firestore のデータを更新 (Update)

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

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

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

// ---------------------------------------------------------------
func get_current_date_proc () string {
    now := time.Now ()
    fmt.Printf ("%s\t" ,now)
    fmt.Printf ("%d-%d-%d\n" ,now.Year (),now.Month(),now.Day())
    today := strconv.Itoa (now.Year()) + "-" +
        fmt.Sprintf ("%d",now.Month()) + "-" +
        strconv.Itoa (now.Day())

    return  today
}

// ---------------------------------------------------------------
func main() {
    fmt.Fprintf (os.Stderr,"*** 開始 ***\n")
    key_in := os.Args[1]
    population_in,_ := strconv.Atoi (os.Args[2])
    fmt.Printf ("key_in = %s\t" , key_in)
    fmt.Printf ("population_in = %d\n" , population_in)
    // 初期化
    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)
    }

dsnap, err := client.Collection("cities").Doc(key_in).Get(ctx)
if err != nil {
        log.Fatalf("Failed : %v", err)
}

mm := dsnap.Data()
fmt.Printf("Document data: %#v\n", mm)

name_aa := dsnap.Data()["name"]

today := get_current_date_proc ()


 _, err = client.Collection("cities").Doc(key_in).Set(ctx, map[string]interface{}{
    "name":  name_aa,
    "population": population_in,
    "date_mod": today,
    })
    if err != nil {
        log.Fatalf("Failed adding alovelace: %v", err)
    }

    // 切断
    defer client.Close()

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

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

実行コマンド

project_id="project-dec16-2020"
echo $project_id
export GOOGLE_CLOUD_PROJECT=$project_id
#
go run firestore_update.go t0926 5134900
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