go - 将 firestore "integer_value"转换为整数

标签 go google-cloud-firestore count

使用 Golang Firestore 1.8 库,我尝试使用 Google 去年秋天推出的 Firestore 的新 count() 函数。这些文档似乎还没有示例,不是我发现的,但我拼凑了一些有点可行的代码,这些代码几乎让我完成了所有工作,只是没有实际生成一个整数。该片段底部的“result[userCountAlias]”值是我感兴趣的转换为整数的值,但我不太确定如何转换。当然,我可以将它作为一个字符串,在冒号上拆分,然后解析它,但这看起来很难看。

任何提示将不胜感激!

非常感谢。

func (s UserService) Count(labID string) (int64, error) {

    if s.DB == nil {
        return -1, customerrors.ErrDatabaseMissing
    }

    query := s.DB.
        Collection(CollectionUsers).
        Where("lab_id", "==", labID)


    userCountAlias := "userCount"

    ag := query.NewAggregationQuery()

    //result is a firestore.AggregationResult, which seems to consist of just a 
    //map[string]interface{}
    result, err := ag.WithCount(userCountAlias).Get(s.Ctx)

    if err != nil {
        return -1, err
    }

    v := result[userCountAlias]//How do I cast this to an integer?
    fmt.Printf("Type = %v", v) //Prints "Type = integer_value:379"

    return -1, nil
}

最佳答案

尝试 fmt.Printf("Type = %T", v) 找出 v 的类型。

v 最有可能是 firestorepb.Value 类型。请注意,这在 1.8 中尚不可用。尝试将 cloud.google.com/go/firestore 升级到最新版本(目前为 1.9)。

package main

import (
    "fmt"

    "cloud.google.com/go/firestore/apiv1/firestorepb"
)

func main() {
    var v interface{} = &firestorepb.Value{
        ValueType: &firestorepb.Value_IntegerValue{
            IntegerValue: 379,
        },
    }

    fmt.Printf("%T\n", v) // *firestorepb.Value
    fmt.Printf("%v\n", v) // integer_value:379

    if v, ok := v.(*firestorepb.Value); ok {
        fmt.Printf("%v\n", v.GetIntegerValue()) // 379
    }
}

官方存储库中的测试以相同的方式检索值。请参阅TestIntegration_CountAggregationQuery .

关于go - 将 firestore "integer_value"转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75982265/

相关文章:

arrays - 在GO中解析json对象数组

go - 在 Go 中计算 hashCode

firebase - 如何解决错误 路径中不得包含//。 Firestore 抖动错误

sql - 统计 PostgreSQL 中枚举的所有值

Mysql Between Clause inside Case when语句并计算列中的项目数

amazon-web-services - 异步调用 AWS Lambda 不会产生任何日志

go - 缺少数据Hyperledger Fabric Chaincode

firebase - 如何在一个流中合并多个流

javascript - React Hooks + Firebase Firestore onSnapshot - 正确使用带有反应钩子(Hook)的 firestore 监听器

mysql - 统计不同表中的违规次数