将Mongo 128位十进制解码为Go语言。

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

Decode Mongo 128-bit Decimal to Go

问题

在Mongodb中,我有这个字段:

units: NumberDecimal('1'),

在Go中映射为:

Units         float64 `json:"units"`

我正在尝试使用以下代码从Go中读取数据:

var result dbo.Invoice
coll := client.Database("hobbit").Collection("customer")
filter := bson.D{{"_id", code}}
err = coll.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
    if err == mongo.ErrNoDocuments {
        return model.Customer{}, fmt.Errorf("invoice %s not found", code)
    }
    return model.Customer{}, fmt.Errorf("reading invoice %s from database: %s", code, err)
}

然后我得到了这个错误:

Error: error un-marshalling invoice F-3945: error decoding key lines.0.units: cannot decode 128-bit decimal into a float32 or float64 type

我尝试使用bsoncodec注册转换:

registryBuilder := bsoncodec.NewRegistryBuilder()
registryBuilder.RegisterTypeMapEntry(bsontype.Decimal128, reflect.TypeOf(float64(0)))

但仍然得到相同的错误。

英文:

In Mongodb I have this field:

units: NumberDecimal('1'),

Mapped in Go to:

Units         float64 `json:"units"`

I'm trying to read the data from Go with:

	var result dbo.Invoice
	coll := client.Database("hobbit").Collection("customer")
	filter := bson.D{{"_id", code}}
	err = coll.FindOne(context.TODO(), filter).Decode(&result)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return model.Customer{}, fmt.Errorf("invoice %s not found", code)
		}
		return model.Customer{}, fmt.Errorf("reading invoice %s from database: %s", code, err)
	}

And I get this error

Error: error un-marshalling invoice F-3945: error decoding key lines.0.units: cannot decode 128-bit decimal into a float32 or float64 type

I tried to register the conversion with bsoncodec:

registryBuilder := bsoncodec.NewRegistryBuilder()
registryBuilder.RegisterTypeMapEntry(bsontype.Decimal128, reflect.TypeOf(float64(0)))

And still getting the same error

答案1

得分: 5

应该是

Units primitive.Decimal128 `json:"units"`

这是NumberDecimal的数据类型。

英文:

It should be

Units primitive.Decimal128 `json:"units"`

That's the data type for NumberDecimal

huangapple
  • 本文由 发表于 2021年12月18日 02:37:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/70397507.html
匿名

发表评论

匿名网友

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

确定