My goal is to implement this code. Except instead of using sql I want to use mongoDB. I think there is an issue with how I handle my sessions.
I'm trying to use mgo to insert some user data into MongoDB via a Rest API. Whenever I open the mongo shell and run the show dbs command, the poll DB is not displayed. I'm using Postman to test the Rest API. Any ideas what am I might be doing wrong in the insertion process? I tried creating the collection first in the mongo shell and then running the CreateUser function but I still didnt see the poll DB get created.
User
type User struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email"`
}
UserDAO
type UserDAO struct {
session *mgo.Session
}
Creating a session
func GetMongoSession() *mgo.Session {
if mgoSession == nil {
var err error
mgoSession, err = mgo.Dial("localhost")
mgoSession.SetMode(mgo.Monotonic, true)
if err != nil {
log.Fatal("Failed to start the Mongo session.")
}
}
return mgoSession.Clone()
}
I pass a User struct into the CreateUser function that I create using Postman:
{
"username":"uname",
"password":"pass",
"email":"[email protected]"
}
Then I just respond with the same struct and receive this output:
{
"id": "",
"username": "uname",
"password": "pass",
"email": "[email protected]"
}
Creating a user
func (dao *UserDAO) CreateUser(u *User) (*User, error) {
//return errors.New("Not implemented")
// Get "users" collection
dao.session = GetMongoSession()
c := dao.session.DB("poll").C("user")
defer dao.session.Close()
//u.Id = bson.NewObjectId()
err := c.Insert(u)
if err != nil {
return nil, err
}
return u, nil
}
Http handler function
func (h *Handler) CreateUserReq(w http.ResponseWriter, r *http.Request) {
// create new user using information from the Request object
var user User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
panic(err)
}
defer r.Body.Close()
// Create new User
u, err := h.UserService.CreateUser(&user)
if err != nil {
panic(err)
}
json.NewEncoder(w).Encode(*u)
}
Output of show dbs
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
&uin your function of insertdao *UserDAOdefined in your code