mongodb - 为什么 mgo 不能正确解码我的结构?

标签 mongodb go bson mgo

早些时候我发布了this question询问使用 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.v2 命令,所以我希望它是最新的,这样的错误不会出现在“ HitTest 门的 MongoDB 驱动程序”中。

最佳答案

GetBSON方法应该返回要编码的值,而不是编码产生的二进制数据。这就是为什么它的第一个结果类型是 interface{} 而不是 []byte

关于mongodb - 为什么 mgo 不能正确解码我的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895854/

相关文章:

javascript - 在 MongoDB 中匹配一组包含数组的项目

python - 如何从 python 中使用 mongolab 附加组件到 Heroku?

json - 在 Go 中将 float64 编码到 json

go - 关闭持久连接的正确方法是什么?

string - 如何检查golang模板中字符串的空值

c# - 检查 BsonValue 是否不为空

node.js - 如何在终端重启mongodb?

mongodb - 未在ElasticSearch中添加Mongo '_id'字段

c# - BsonSerializer.Deserialize<T>(bsonDocument) - 子对象的 Id 字段导致异常

java - java的BSON库?