douju2053 2017-08-04 13:52
浏览 65
已采纳

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.

Objects in Collection

  • 写回答

1条回答 默认 最新

  • dongxiane0395 2017-08-04 13:58
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭