How i can update data firebase with specific key in golang?

huangapple go评论75阅读模式
英文:

How i can update data firebase with specific key in golang?

问题

我正在使用golang和firego连接到Firebase。我想要将我的数据Status从ON更新为OFF,键为IDAgent: 7。这是我的数据库结构。

[图片]

假设:我不知道子节点active_chat。如何在active_chat/-Koja8GuFplEN3kjbfPO中更新IDAgent为7的数据?

我尝试了这段代码

x := map[string]string{"Status": "OFF"}
ref.OrderBy("IDAgent").EqualTo("7").Update(x)

但是这段代码查询错误。
[图片]: https://i.stack.imgur.com/VWM4J.png

英文:

I am using golang and firego for connecting to Firebase. I want to update my data Statusfrom ON to OFF with key IDAgent: 7. This is my Database Structure

[Image]

Assumption : I don't know child active_chat. How can i update data in active_chat/-Koja8GuFplEN3kjbfPO where IDAgent = 7

I have tried this code

x := map[string]string{"Status": "OFF"}
ref.OrderBy("IDAgent").EqualTo("7").Update(x)

but this code wrong query.
[Image]: https://i.stack.imgur.com/VWM4J.png

答案1

得分: 1

你可以通过两种方式来实现,根据Firebase文档和firego客户端库。下面的答案是根据firego的README.md草拟的。

注意:你没有提供完整的路径结构,我根据截图草拟了答案。所以请根据你的JSON路径进行更新。

方法一:

f := firego.New("https://my-firebase-app.firebaseIO.com/active-chat/Koja8GuFpIEN3kjbfPO.json", nil)

x := map[string]string{
   "Status": "OFF",
}
if err := f.Update(x); err != nil {
  log.Fatal(err)
}

方法二:

f := firego.New("https://my-firebase-app.firebaseIO.com", nil)
f = f.Ref("/active-chat/Koja8GuFpIEN3kjbfPO.json")

x := map[string]string{
   "Status": "OFF",
}
if err := f.Update(x); err != nil {
  log.Fatal(err)
}
英文:

In two ways you can do, as per Firebase doc with firego client library. Drafted answer based on from firego README.md.

Note: You have not provided the complete path of the structure, I have drafted the answer based on screenshot. So update your JSON path accordingly.

Approach 1:

f := firego.New("https://my-firebase-app.firebaseIO.com/active-chat/Koja8GuFpIEN3kjbfPO.json", nil)

x := map[string]string{
   "Status": "OFF",
}
if err := f.Update(x); err != nil {
  log.Fatal(err)
}

Approach 2:

f := firego.New("https://my-firebase-app.firebaseIO.com", nil)
f = f.Ref("/active-chat/Koja8GuFpIEN3kjbfPO.json")

x := map[string]string{
   "Status": "OFF",
}
if err := f.Update(x); err != nil {
  log.Fatal(err)
}

答案2

得分: 1

2022年的更新:

package main

import (
	"context"
	"fmt"
	"time"

	firestore "cloud.google.com/go/firestore"
	firebase "firebase.google.com/go"

	"google.golang.org/api/option"
)

type (
	myDocument struct {
		Cars       []Car  `firestore:"cars"`
		carsCount  int64  `firestore:"car_count"`
		UpdateTime string `firestore:"update_time"`
	}
	Car struct {
		Name      string `firestore:"name"`
		YearBuilt string `firestore:"year_built"`
	}
)

func getFirebaseClient(ctx context.Context) (*firestore.Client, error) {
	sa := option.WithCredentialsFile("Path_To_Firebase_Key")

	// 使用管理员权限初始化 Firebase 应用
	app, err := firebase.NewApp(ctx, nil, sa)

	if err != nil {
		err = fmt.Errorf("getFirestoreClient 失败:%s", err)
		return nil, err
	}
	// 创建客户端
	client, err := app.Firestore(ctx)
	if err != nil {
		err = fmt.Errorf("连接到 Firestore 失败:%v", err)
		return nil, err
	}

	return client, nil
}

func main() {
	// 创建上下文
	ctx := context.Background()

	// 获取 Firebase 客户端
	client, err := getFirebaseClient(ctx)
	if err != nil {
		panic(err)
	}

	// 创建 car 结构体
	newCar := Car{
		"Volvo_Series1",
		"1920",
	}

	// 更新时间
	newTime := time.Now().UTC().Format("Monday, 01-02-2006 15:04:05")

	// 文档更新
	updates := []firestore.Update{
		{Path: "cars", Value: firestore.ArrayUnion(newCar)},
		{Path: "car_count", Value: firestore.Increment(1)},
		{Path: "update_date", Value: newTime},
	}

	// 选项 A)
	// 创建集合引用
	collectionRef := client.Collection("cars")

	// 创建文档引用
	docRef := collectionRef.Doc("12345")

	// 更新文档
	_, err = docRef.Update(ctx, updates)
	if err != nil {
		err := fmt.Errorf("更新文档失败:%s,来自 %s 集合 %v", docRef.ID, docRef.Parent.ID, err)
		panic(err)
	}

	// 选项 B)
	_, err = client.Collection("cars").Doc("12345").Update(ctx, updates)
	if err != nil {
		err := fmt.Errorf("更新文档失败:%s,来自 %s 集合 %v", docRef.ID, docRef.Parent.ID, err)
		panic(err)
	}
}

这是一个用于更新 Firestore 文档的 Go 代码示例。它使用 Google Cloud 的 Go 客户端库和 Firebase 库。代码中的 getFirebaseClient 函数用于获取 Firestore 客户端实例。myDocument 结构体定义了文档的结构,其中包含一个 Cars 字段和一个 carsCount 字段。Car 结构体定义了汽车的属性。main 函数中的代码演示了如何使用 Firestore 客户端更新文档。你可以根据自己的需求进行修改和使用。

英文:

Update for 2022:

package main
import (
"context"
"fmt"
"time"
firestore "cloud.google.com/go/firestore"
firebase "firebase.google.com/go"
"google.golang.org/api/option"
)
type (
myDocument struct {
Cars       []Car  `firestore:"cars"`
carsCount  int64  `firestore:"car_count"`
UpdateTime string `firestore:"update_time"`
}
Car struct {
Name      string `firestore:"name"`
YearBuilt string `firestore:"year_built"`
}
)
func getFirebaseClient(ctx context.Context) (*firestore.Client, error) {
sa := option.WithCredentialsFile("Path_To_Firebase_Key")
// Initialize firebase app with admin privileges
app, err := firebase.NewApp(ctx, nil, sa)
if err != nil {
err = fmt.Errorf("getFirestoreClient failed: %s", err)
return nil, err
}
// Create client
client, err := app.Firestore(ctx)
if err != nil {
err = fmt.Errorf("failed to connect to firestore: %v", err)
return nil, err
}
return client, nil
}
func main() {
// Create context
ctx := context.Background()
// Get firebase client
client, err := getFirebaseClient(ctx)
if err != nil {
panic(err)
}
// Create car struct
newCar := Car{
"Volvo_Series1",
"1920",
}
// Update time
newTime := time.Now().UTC().Format("Monday, 01-02-2006 15:04:05")
// Updates to document
updates := []firestore.Update{
{Path: "cars", Value: firestore.ArrayUnion(newCar)},
{Path: "car_count", Value: firestore.Increment(1)},
{Path: "update_date", Value: newTime},
}
// OPTION A)
// Create collection reference
collectionRef := client.Collection("cars")
// Create document reference
docRef := collectionRef.Doc("12345")
// Update document
_, err = docRef.Update(ctx, updates)
if err != nil {
err := fmt.Errorf("failed updating document: %s from %s collection %v", docRef.ID, docRef.Parent.ID, err)
panic(err)
}
// OPTION B)
_, err = client.Collection("cars").Doc("12345").Update(ctx, updates)
if err != nil {
err := fmt.Errorf("failed updating document: %s from %s collection %v", docRef.ID, docRef.Parent.ID, err)
panic(err)
}
}

huangapple
  • 本文由 发表于 2017年7月11日 12:31:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/45025447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定