Golang mgo 获取空对象 [英] Golang mgo getting empty objects

查看:26
本文介绍了Golang mgo 获取空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 Go API 开发.我有一个在 Docker 容器中运行的 MongoDB 实例.我正在尝试遵循一些指南,但在简单的查询上失败了.我不完全理解这里使用 BSON 和 JSON 标签.我知道这些术语是什么意思.所以这是我的代码.

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

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

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.

推荐答案

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

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"` 
}

默认情况下,当从 MongoDB 转换/存储/检索结构值时,将使用字段名称.如果您想使用不同的名称,您可以使用 标签 告诉字段应该映射到什么名称.

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.

这篇关于Golang mgo 获取空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆