user3212497
user3212497

Reputation:

Go to a particular document in MongoDB using golang

I am having a problem to go to a particular document (in this case an event) using gorilla and mgo.

The event model :

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"`

The event handler

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 route in main

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

The View (html)

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

The Error

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

What I want is to go to the route /event/view/Id and show the particular page of the event.

My guess is that there is probably a data type parsing problem, but still tried a few ways and failed.

Upvotes: 1

Views: 676

Answers (1)

CrazyCrow
CrazyCrow

Reputation: 4235

Try to remove spaces from your router as "eventId" != " eventId "

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

Upvotes: 1

Related Questions