Home > front end >  Decode Mongo 128-bit Decimal to Go
Decode Mongo 128-bit Decimal to Go

Time:12-22

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

CodePudding user response:

It should be

Units primitive.Decimal128 `json:"units"`

That's the data type for NumberDecimal

  • Related