Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mongodb - Golang mgo getting empty objects

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...