mongodb - 防止 mgo/bson Unmarshal 清除未导出的字段

标签 mongodb go unmarshalling mgo

我尝试使用从 MongoDb 获取的内容填充结构的导出字段。 -使用labix.org/v2/mgo的数据库包。

mgo 使用 labix.org/v2/mgo/bson包来解码数据。但解码器将所有未导出的字段设置为零值。

有什么办法可以阻止这种行为吗?

工作示例:

package main

import (
    "fmt"
    "labix.org/v2/mgo/bson"
)

type Sub struct{ Int int }

type Player struct {
    Name       string
    unexpInt   int
    unexpPoint *Sub
}

func main() {
    dta,err := bson.Marshal(bson.M{"name": "ANisus"})
    if err != nil {
        panic(err)
    }

    p := &Player{unexpInt: 12, unexpPoint: &Sub{42}}

    fmt.Printf("Before: %+v\n", p)
    err = bson.Unmarshal(dta, p)
    if err != nil {
        panic(err)
    }
    fmt.Printf("After: %+v\n", p)
}

输出:

Before: &{Name: unexpInt:12 unexpPoint:0xf84005f500}
After: &{Name:ANisus unexpInt:0 unexpPoint:<nil>}

最佳答案

这是不可能的。如您所见in the source codestruct 值在填充任何字段之前显式设置为零值。

没有选项可以禁用此行为。它可能是为了确保 Unmarshal() 的结果仅取决于 BSON 数据而不取决于任何先前状态。

关于mongodb - 防止 mgo/bson Unmarshal 清除未导出的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388210/

相关文章:

mongodb - 如何改善使用数组聚合时糟糕的 MongoDB 查询性能

xml - 如何将没有根/父元素的 XML 转换为结构体?

json - 如何使用 Golang 解码动态 json 对象

macos - 什么是 macbook 网络摄像头的正确路径

go - 如果传入的数组为 &val 然后转换为接口(interface){},则更新数组元素

go - 为什么 Go panic() 将 interface{} 而不是 ...interface{} 作为参数?

c# - 如何在 c# 中调用此 c 函数(解码返回结构)?

mongodb - apollostack/graphql-server - 如何从解析器获取查询中请求的字段

mongodb - 在 MongoDB 中获取数组的第一个和最后一个元素

mongodb - 在一个 MongoDB 聚合查询中进行排序和分组