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

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

Decode Mongo 128-bit Decimal to Go

问题

在Mongodb中,我有这个字段:

  1. units: NumberDecimal('1'),

在Go中映射为:

  1. Units float64 `json:"units"`

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

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

然后我得到了这个错误:

  1. 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注册转换:

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

但仍然得到相同的错误。

英文:

In Mongodb I have this field:

  1. units: NumberDecimal('1'),

Mapped in Go to:

  1. Units float64 `json:"units"`

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

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

And I get this error

  1. 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:

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

And still getting the same error

答案1

得分: 5

应该是

  1. Units primitive.Decimal128 `json:"units"`

这是NumberDecimal的数据类型。

英文:

It should be

  1. 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:

确定