Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 为什么mgo不能正确地解组我的结构?_Mongodb_Go_Bson_Mgo - Fatal编程技术网

Mongodb 为什么mgo不能正确地解组我的结构?

Mongodb 为什么mgo不能正确地解组我的结构?,mongodb,go,bson,mgo,Mongodb,Go,Bson,Mgo,早些时候,我发布了关于使用mgo在Go中编写自定义BSON编组/解编组的问题。现在我来测试它,我想我碰到了一个更大的问题。我的所有结构都将值解组为零 这是我的货币结构,包含bson.Getter和bson.Setter的实现: type Currency struct { value decimal.Decimal //The actual value of the currency. currencyCode string //The ISO c

早些时候,我发布了关于使用mgo在Go中编写自定义BSON编组/解编组的问题。现在我来测试它,我想我碰到了一个更大的问题。我的所有结构都将值解组为零

这是我的货币结构,包含bson.Getter和bson.Setter的实现:

type Currency struct {
    value        decimal.Decimal //The actual value of the currency.
    currencyCode string          //The ISO currency code.
}

/*
GetBSON implements bson.Getter.
*/
func (c Currency) GetBSON() (interface{}, error) {
    f, _ := c.Value().Float64()
    return bson.Marshal(struct {
        Value        float64 `json:"value" bson:"value"`
        CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`
    }{
        Value:        f,
        CurrencyCode: c.currencyCode,
    })
}

/*
SetBSON implements bson.Setter.
*/
func (c *Currency) SetBSON(raw bson.Raw) error {
    decoded := new(struct {
        Value        float64 `json:"value" bson:"value"`
        CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`
    })

    fmt.Println(string(raw.Data))
    bsonErr := raw.Unmarshal(decoded)

    if bsonErr == nil {
        fmt.Println("Debug: no error returned.")
        fmt.Println(decoded)
        c.value = decimal.NewFromFloat(decoded.Value)
        c.currencyCode = decoded.CurrencyCode
        return nil
    } else {
        return bsonErr
    }
}

通过查看原始数据,它可以正确封送,但在解封时,生成的结构就是空的。你知道我哪里做错了吗?我昨天使用了go-get-gopkg.in/mgo.v2command,所以我希望它是最新的,这样的错误不会出现在最热门的MongoDB驱动程序中。

该方法应该返回要封送的值,而不是封送后产生的二进制数据。这就是为什么它的第一个结果类型是接口{},而不是[]字节。

该方法应该返回要封送的值,而不是封送后产生的二进制数据。这就是为什么它的第一个结果类型是接口{},而不是[]字节。

您的getter和setter是不对称的。is GetBSON返回一个[]字节,SetBSON需要解组[]字节类型,然后再次进行解组以将[]字节转换为struct。您的getter和setter不对称。is GetBSON返回一个[]字节,SetBSON需要解组一个[]字节类型,然后再次进行解组以将[]字节转换为结构。Muchas gracias:我摆脱了bson。对返回结构进行封送处理后,它立即生效。嗨,我如何使用此驱动程序实现同样的效果?go.mongodb.org/mongo-driver/mongoMuchas-gracias:我在return结构中去掉了bson.Marshal,它立即起了作用。嗨,我如何使用这个驱动程序实现同样的效果?go.mongodb.org/mongo-driver/mongo