Created
March 18, 2020 13:53
-
-
Save yutakahashi114/ff7aa71180703bedb65f63673e299414 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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