首页 > 解决方案 > 将嵌套结构添加到 Firestore

问题描述

我正在尝试向 Firestore 添加一个嵌套结构,由于某种原因,添加的内容都是非结构,看起来像:

在此处输入图像描述

结构看起来像这样:

type Status struct {
    Title   string `json:"title,omitempty" firestore:"title,omitempty"`
    Message string `json:"message,omitempty" firestore:"title,omitempty"`
}

type Config struct {
    Name   string `json:"name,omitempty" firestore:"name,omitempty"`
    Status Status `json:"status,omitempty" firestore:"status,omitempty"`
}

代码看起来像这样:

import (
    "context"

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

func main() {

    configuration := Config{
        Name: "Test",
        Status: Status{
            Title:   "hello",
            Message: "hi",
        },
    }

    ctx := context.Background()
    config := firebase.Config{
        ProjectID:     "",
        StorageBucket: "",
    }
    opt := option.WithCredentialsFile("firebase_config.json")
    app, err := firebase.NewApp(ctx, &config, opt)
    if err != nil {
        panic(err)
    }

    // Get an auth client from the firebase.App
    client, err := app.Firestore(ctx)
    if err != nil {
        panic(err)
    }

    _, _, err = client.Collection("forecast").Add(ctx, configuration)
    if err != nil {
        panic(err)
    }
}

上面的代码仅适用于不在嵌套结构中的元素。

对此的任何帮助将不胜感激

更新 1

Status不是子集合而是对象,例如:

{
  "name": "Test",
  "status": {
      "title": "hello",
      "message": "hi"
   }
}

标签: firebasegogoogle-cloud-firestore

解决方案


根据对评论的讨论,将此作为社区 Wiki 答案发布。

这种情况的解决方案似乎是在 type 字段中手动添加值Map。实现该目标的步骤如下:访问 Firebase 控制台 -> Firestore -> 创建文档 -> 添加类型的字段Map。按照这个顺序,可以创建一个 type 的字段,该字段Map具有添加数据所需的格式,如问题描述中所述。

有关此类型、其工作原理、排序选项等的更多信息,可以在此处的官方文档中找到:支持的数据类型


推荐阅读