Go mgo无法存储对象。

huangapple go评论77阅读模式
英文:

Go mgo not storing object

问题

使用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。

英文:

Using mgo I'm unable to store any meaningful data. Only the _id gets stored

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)
}

The result in Mongo is just the _id field - no sign of "Joe".


Using go 1.1.2 on Arch linux, MongoDB 2.4.6.

答案1

得分: 13

type Person struct {
name string
age int
}

mgo包无法访问结构体中未导出(小写)的字段(即除了定义结构体的包之外的其他包都不能访问)。您需要将它们导出(首字母必须大写),像这样:

type Person struct {
Name string
Age int
}

如果您希望在数据库中将字段名设置为小写,您必须为它们提供一个结构标签,像这样:

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

请参阅名称的文档

在Go语言中,名称与其他任何语言一样重要。它们甚至具有语义效果:名称在包外的可见性取决于其首字母是否大写。[...]

编辑

Gustavo Niemeyer(mgobson包的作者)在评论中指出,与json包不同,bson编组器在提交到数据库时会将所有结构字段名转换为小写,因此这个答案中的最后一步实际上是多余的。

英文:
type Person struct {
    name string
    age  int
}

The mgo package can't access unexported (lowercase) fields of your struct (i.e. no other package than the one the struct is defined in can). You need to export them (first letter must be upper case), like this:

type Person struct {
    Name string 
    Age  int    
}

If you wish to have the field names in lower case in the DB you must provide a struct tag for them, like this:

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

See the 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. [...]

EDIT:

Gustavo Niemeyer (author of the mgo and bson packages) noted in the comments that unlike the json package, the bson marshaller will lowercase all struct field names when commiting to the database, effectively making the last step in this answer superfluous.

huangapple
  • 本文由 发表于 2013年8月30日 21:04:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/18533619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定