Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yutakahashi114/ff7aa71180703bedb65f63673e299414 to your computer and use it in GitHub Desktop.
Save yutakahashi114/ff7aa71180703bedb65f63673e299414 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, os.Getenv("PROJECT_ID"))
if err != nil {
log.Fatal(err)
}
create(ctx, client)
print(ctx, client)
}
func create(ctx context.Context, client *firestore.Client) {
ref, _, err := client.Collection("companies").Add(ctx, map[string]interface{}{
"name": "test_company",
})
if err != nil {
log.Fatal(err)
}
for i := 0; i < 5; i++ {
_, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
"name": "test_" + strconv.Itoa(i),
"company_id": ref.ID,
})
if err != nil {
log.Fatal(err)
}
}
}
func print(ctx context.Context, client *firestore.Client) {
companies, err := client.Collection("companies").Documents(ctx).GetAll()
if err != nil {
log.Fatal(err)
}
for _, company := range companies {
fmt.Println(company.Data())
}
users, err := client.Collection("users").Documents(ctx).GetAll()
if err != nil {
log.Fatal(err)
}
for _, user := range users {
fmt.Println(user.Data())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment