mongodb - 使用 golang 转到 MongoDB 中的特定文档

标签 mongodb go mgo gorilla

我在使用 gorilla 和 mgo 转到特定文档(在本例中为事件)时遇到问题。

事件模型:

Id              bson.ObjectId `bson:"_id,omitempty"`
Email           string        `bson:"user_email"`
Name            string        `bson:"name"`
Category        string        `bson:"category"`
Description     string        `bson:"description"`
Status          string        `bson:"status"`

事件处理器

func ViewEventHandler(w http.ResponseWriter, r *http.Request) {
  vars := mux.Vars(r)
  eventId := vars["eventId"]
  session, err := mgo.Dial("mongodb://DATABASE_URL")

  defer session.Close()
  session.SetMode(mgo.Monotonic, true)
  c := session.DB("DATABASE_NAME").C("event")

  result := model.EventModel{}

  // the following line is probably the problem
  err = c.FindId(bson.ObjectIdHex(eventId)).One(&result)

  if r.Method == "GET" {
    t, _ := template.ParseFiles("templates/view/event.html");
    t.Execute(w, result);
  }
}

主要的 gorilla 路线

router.HandleFunc("/event/view/{ eventId }/", handlers.ViewEventHandler)

View (html)

<td><a href="/event/view/{{ .Id.Hex }}/">{{ .Name }}</a></td>

错误

2016/01/30 22:06:01 http: panic serving 127.0.0.1:41254: Invalid input to ObjectIdHex: ""

我想要的是转到路由/event/view/Id 并显示事件的特定页面。

我的猜测是可能是数据类型解析有问题,但还是尝试了几种方法都失败了。

最佳答案

尝试从您的路由器中删除空格作为 "eventId"!= "eventId "

router.HandleFunc("/event/view/{eventId}/", handlers.ViewEventHandler)

关于mongodb - 使用 golang 转到 MongoDB 中的特定文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35107134/

相关文章:

回调中的Javascript变量范围?

go - 获取在 Go 中执行函数所花费的时间

go - 从Go程序访问AKS kubeconfig文件

go - socket.go 中 SimpleQuery 中的本地互斥锁

mongodb - 在 mongo 中设置单个位,以存储位掩码

c# - MongoDB 文本搜索使用 c# Driver 2.4.4

MongoDB 基于每个元素对来自多个文档的数组求和

go - 在 html/templates 中有没有办法在所有页面上有一个恒定的页眉/页脚?

mongodb - 多个 session.Copy() 后 mgo 连接泄漏

json - 在 Go 中流式传输 BSON->JSON HTTP 回复?