dongyan7950 2015-12-21 12:54
浏览 55

Golang,mgo更新用户详细信息

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)
    }
}
  • 写回答

2条回答 默认 最新

  • duanchui1955 2016-09-11 15:36
    关注

    Well I see at least one problem a that is the case sensitive queries. So if your struct uses lowercase keys in json, you must use a lowercase one.

    // This shoud match 
    // against the "Name" property
    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(),
     }}
    
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装