Golang mgo 获取空对象

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

Golang mgo getting empty objects

问题

我正在尝试学习Go API开发。我在Docker容器中运行了一个MongoDB实例。我尝试按照一些指南进行操作,但在简单查询上失败了。我不完全理解这里的BSON和JSON标签的用法。我知道这些术语的含义。下面是我的代码。

import (
	"fmt"
	"time"

	"gopkg.in/mgo.v2/bson"
)

const (
	hosts      = "localhost:27017"
	database   = "my_database"
	username   = "dev1"
	password   = "password123"
	collection = "users"
)

type users struct {
	user string `bson:"user" json:"user"`
	data string
}

func main() {

	fmt.Println("Starting Application!")

	info := &mgo.DialInfo{
		Addrs:    []string{hosts},
		Timeout:  60 * time.Second,
		Database: database,
		Username: username,
		Password: password,
	}

	session, err1 := mgo.DialWithInfo(info)
	if err1 != nil {
		panic(err1)
	}
	defer session.Close()

	col := session.DB(database).C(collection)

	var user users
	var books []users
	var username = "cat"

	col.Insert(&users{user: "dog", data: "blah"})
	err3 := col.Find(bson.M{"user": username}).One(&user)
	fmt.Println(user)
	fmt.Println(err3)
	count, err2 := col.Count()
	if err2 != nil {
		panic(err2)
	}
	fmt.Println(fmt.Sprintf("Messages count: %d", count))

	fmt.Println(user)
	col.Find(bson.M{}).All(&books)
	fmt.Println(books)
}

基本上,我在打印行上得到了空对象,但是得到了正确的消息计数。如果有帮助,我是用robomongo插入的对象。

Golang mgo 获取空对象

英文:

I'm trying to learn Go API development. I have a MongoDB instance running in a Docker container. I'm trying to follow a few guides but am failing on simple queries. I don't fully understand the use of BSON and JSON tags here. I do know what those terms mean. So here is my code.

import (
"fmt"
"time"
"gopkg.in/mgo.v2/bson"
)
const (
hosts      = "localhost:27017"
database   = "my_database"
username   = "dev1"
password   = "password123"
collection = "users"
)
type users struct {
user string `bson:"user" json:"user"`
data string
}
func main() {
fmt.Println("Starting Application!")
info := &mgo.DialInfo{
Addrs:    []string{hosts},
Timeout:  60 * time.Second,
Database: database,
Username: username,
Password: password,
}
session, err1 := mgo.DialWithInfo(info)
if err1 != nil {
panic(err1)
}
defer session.Close()
col := session.DB(database).C(collection)
var user users
var books []users
var username = "cat"
col.Insert(&users{user: "dog", data: "blah"})
err3 := col.Find(bson.M{"user": username}).One(&user)
fmt.Println(user)
fmt.Println(err3)
count, err2 := col.Count()
if err2 != nil {
panic(err2)
}
fmt.Println(fmt.Sprintf("Messages count: %d", count))
fmt.Println(user)
col.Find(bson.M{}).All(&books)
fmt.Println(books)
}

Basically I'm getting empty objects on the print line but am getting the correct Message count. I inserted the objects with robomongo if that helps.

Golang mgo 获取空对象

答案1

得分: 9

你必须导出结构体的字段,否则它们将被mgo包忽略。将users的字段更改为UserData

type users struct {
    User string `bson:"user" json:"user"`
    Data string `bson:"data" json:"data"` 
}

默认情况下,当从MongoDB转换/存储/检索结构体值时,使用字段名。如果你想使用不同的名称,可以使用标签来指定字段应该映射到哪些名称。

英文:

You must export fields of structs, else they are ignored by the mgo package. Change fields of users to User and Data.

type users struct {
User string `bson:"user" json:"user"`
Data string `bson:"data" json:"data"` 
}

By default when a struct value is transformed / stored / retrieved from MongoDB, the field name is used. If you want to use different names, you may use tags to tell what names should the fields map to.

huangapple
  • 本文由 发表于 2017年8月4日 21:52:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/45508642.html
匿名

发表评论

匿名网友

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

确定