I have been trying to query my mongodb database but it seems to not work properly.
This is my code. I am not sure if the struct is to be used the way I am doing it right now.
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"os"
)
type userInfo struct {
username string `bson:"username"`
pass string `bson:"pass"`
}
func connect() (session *mgo.Session) {
connectURL := "localhost:27017"
session, err := mgo.Dial(connectURL)
if err != nil {
fmt.Printf("Can't connect to mongo, go error %v\n", err)
os.Exit(1)
}
session.SetSafe(&mgo.Safe{})
return session
}
func main() {
session := connect()
defer session.Close()
result := userInfo {}
collection := session.DB("test_db").C("userlogin")
err := collection.Find(bson.M{"username": "super_sam"}).One(&result)
if err != nil {
log.Println("Not in db")
return
}
fmt.Println("Username:%s", result.pass)
}
Everything seems perfect based on the tutorials that I have seen so far assuming that the ones inside the literal in the struct is supposed to match the exact usage as in the database which is the way it is stored in the db(i.e. in bson format). I have used the exact names in the collection in the db as in inside the backticks(“username” and “pass”). The username “super_sam” was inserted manually into the collection yet when queried I get the “Not in db” result.
This is what I observed when I checked manually in mongodb shell after I did an insert using golang —
err := collection.Insert(&userInfo{username: “Alex”, pass: “cool”})
show collections
system.indexes
userlogin
db.userlogin.find()
{ “_id” : ObjectId(“57b9e5b4717f3b9cf03b997f”) }
As you can see it is empty other than the default ID that is generated on successful insertion.
Any help would be useful. Thanks in advance.