I have been having some trouble updating a user on a mongodatabase. Basically I want to select the user by username and than edit its details. I am using Gorilla Mux and mgo to connect with MongoDB.
Here is the code:
func ViewUserHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
username := vars["username"]
session, err := mgo.Dial("mongodb://DATABASE_URL")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("studnet").C("user")
result := Person{}
// get the user_id using a hidden field when clicked using javascript
err = c.Find(bson.M{"name": username}).One(&result)
if err != nil {
log.Fatal(err)
}
if r.Method == "GET" {
t, _ := template.ParseFiles("profile.html")
t.Execute(w, result)
}
// update the user profile details
if r.Method == "POST" {
r.ParseForm()
// TODO : update the user
selectedUser := bson.M{"name": username}
updatedUser := bson.M{"$set": bson.M{
"Name": r.Form["username"][0],
"Gender": r.Form["gender"][0],
"Age": r.Form["age"][0],
"CreatedAt": time.Now(),
}}
err = c.Update(selectedUser, updatedUser)
if err != nil {
panic(err)
}
http.Redirect(w, r, "/view/"+username, 301)
}
}