mongodb - Go mgo 不存储对象

标签 mongodb go mgo

使用 mgo我无法存储任何有意义的数据。只有 _id 被存储

type Person struct {
    name string
    age int
}

func main() {
    session, err := mgo.Dial("localhost")
    if err != nil {
        log.Fatal(err)
    }
    defer session.Close()

    p := Person{"Joe", 50}
    ppl := session.DB("rest").C("people")
    ppl.Insert(p)
}

Mongo 中的结果只是 _id 字段 - 没有“Joe”的迹象。


在 Arch linux 上使用 go 1.1.2,MongoDB 2.4.6。

最佳答案

type Person struct {
    name string
    age  int
}

mgo 包无法访问您的结构的未导出(小写)字段(即除了在 can 中定义该结构的包之外,没有其他包)。您需要将它们导出(首字母必须大写),如下所示:

type Person struct {
    Name string 
    Age  int    
}

如果您希望在数据库中使用小写的字段名称,您必须为它们提供结构标记,如下所示:

type Person struct {
    Name string `bson:"name"`
    Age  int    `bson:"age"`
}

参见 documentation on names :

Names are as important in Go as in any other language. They even have semantic effect: the visibility of a name outside a package is determined by whether its first character is upper case. [...]

编辑:

Gustavo Niemeyer(mgobson 包的作者)在评论中指出,与 json 包不同,bson marshaller 将在提交到数据库时将所有结构字段名称小写,有效地使这个答案中的最后一步变得多余。

关于mongodb - Go mgo 不存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18533619/

相关文章:

go - 将 map 转换为 bson

ruby-on-rails - 是否有关于在 Rails (3.0) 中设置 Apple 推送通知服务器的任何教程或指南?

node.js - Mongoose 自定义验证失败

ruby-on-rails - 无法使用 mongoid 和 MongoDB 将新记录保存到我的 Rails 模型中

go - 如何从按特定顺序执行的 N 个 goroutine 中收集值?

docker - 以编程方式检查 Docker 容器进程是否以非零状态结束

mongodb - 在 Go 中使用页码和限制进行分页的最佳做法是什么?

java - 如何使用java在mongoDB中创建一对多

https - 戈朗 : Send http request with certificate

mongodb - 使用 mgo.txn 模拟更新插入