Home >Backend Development >Golang >Convert firestore 'integer_value' to integer

Convert firestore 'integer_value' to integer

PHPz
PHPzforward
2024-02-06 09:10:12784browse

将 firestore“integer_value”转换为整数

Question content

Using the golang firestore 1.8 library, I tried to use the new count() function of firestore launched by Google last fall. The docs don't seem to have examples yet, not that I found, but I cobbled together some somewhat working code that pretty much got me doing everything except actually generating an integer. The "result[usercountalias]" value at the bottom of the snippet is the value I'm interested in converting to an integer, but I'm not quite sure how. Of course, I could make it a string, split on the colon, and then parse it, but that would look ugly.

Any tips would be greatly appreciated!

Thank you so much.

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
}

Correct answer


Tryfmt.printf("type = %t", v) Find outv type.

v Most likely firestorepb.value. Note that this is not available in 1.8 yet. Try upgrading cloud.google.com/go/firestore to the latest version (currently 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
    }
}

Tests in the official repository retrieve values ​​in the same way. See testintegration_countaggregationquery.

The above is the detailed content of Convert firestore 'integer_value' to integer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Golang context switchingNext article:Golang context switching