为什么赢得mgo unmarshall我的结构正确?

时间:2015-06-17 15:23:36

标签: 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命令,所以我希望它是最新的,这样的bug不会出现在"最热门的MongoDB驱动程序中。"。

1 个答案:

答案 0 :(得分:4)

GetBSON方法应该返回要封送的值,而不是由封送它产生的二进制数据。这就是为什么它的第一个结果类型是class cellTabOfTasks: UITableViewCell { @IBOutlet var subject: UILabel! @IBOutlet var dueDate: UILabel! @IBOutlet var status: UILabel! @IBOutlet var priority: UILabel! var colorLabels: UIColor = UIColor.blackColor() { didSet { subject?.textColor = colorLabels dueDate?.textColor = colorLabels status?.textColor = colorLabels priority?.textColor = colorLabels } } } 而不是interface{}