英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论