-2

How do i query polls by id with go-gin and MongoDB, i have tried several methods but i still get errors (not found), can't seem to find a walk around below is my code, with my database on mongoDB:

type Poll struct {
    //ID        string `json:"_id,omitempty"`
    ID        bson.ObjectId     `json:"id,omitempty" bson:"_id,omitempty"`
    Firstname string            `json:"firstname,omitempty"`
    Lastname  string            `json:"lastname,omitempty"`
    Poll      string            `json:"poll,omitempty"`
    //  Address   *Address `json:"address,omitempty"`
}

var (
    // Session stores mongo session
    Session *mgo.Session

    // Mongo stores the mongodb connection string information
    Mongo *mgo.DialInfo
)

const (
    // MongoDBUrl is the default mongodb url that will be used to connect to the
    // database.
    MongoDBUrl = "mongodb://localhost:27017/smartpoll"

        // CollectionPoll holds the name of the poll collection
    CollectionPoll = "polls"
)

// Connect connects to mongodb
func Connect() {
    uri := os.Getenv("MONGODB_URL")

    if len(uri) == 0 {
        uri = MongoDBUrl
    }

    mongo, err := mgo.ParseURL(uri)
    s, err := mgo.Dial(uri)
    if err != nil {
        fmt.Printf("Can't connect to mongo, go error %v\n", err)
        panic(err.Error())
    }
    s.SetSafe(&mgo.Safe{})
    fmt.Println("Connected to", uri)
    Session = s
    Mongo = mongo
}


func init() {
    Connect()
}

func main() {
    port := os.Getenv("PORT")

    if port == "" {
        log.Fatal("$PORT must be set")
    }



    router := gin.Default()
    router.Use(ConnectMiddleware)
    router.GET("/", func (c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "OK"})

    })

    router.GET("/polls/:_id", pollsByID)
    router.Run(":" + port)
}




func ConnectMiddleware(c * gin.Context) {
    c.Set("db", Session.DB(Mongo.Database))
    c.Next()
}

func pollsByID(c * gin.Context) {
    db := c.MustGet("db").(*mgo.Database)
    id := c.Param("id")
    poll := []Poll{}
//  err := db.C(CollectionPoll).Find(id).One(&poll)
    err := db.C(CollectionPoll).Find(bson.M{"_id": id}).One(&poll)



    if err != nil {
        //c.Error(err)
        //panic(err)
      log.Println(err)
    }
    result := gin.H{"payload": poll}
  c.Writer.Header().Set("Content-Type", "application/json")
    c.JSON(200, result)

}

my DB is as follows:

{
    "_id" : ObjectId("58d9cf1cdf353f3d2f5951b4"),
    "id" : "1",
    "firstname" : "Sam",
    "lastname" : "Smith",
    "poll" : "Who is the Richest in the World"
}
Tech-P
  • 1
  • 2

2 Answers2

0

Your ID is an ObjectId, but your input is a string. You need to use bson.ObjectIdHex to parse the string into an ObjectId:

err := db.C(CollectionPoll).FindId(bson.ObjectIdHex(id)).One(&poll)
Adrian
  • 42,911
  • 6
  • 107
  • 99
  • "1" is not a valid BSON ObjectId, and per the documentation I linked to, if it's not valid, `ObjectIdHex` will panic. – Adrian Jul 24 '17 at 18:32
  • OK... what did you change? Are you passing in a valid ObjectId for a document that exists in your collection? When you execute the query manually with the mongo client does it work? – Adrian Jul 24 '17 at 18:44
  • i did this "http://localhost:5000/polls/58d9cf1cdf353f3d2f5951b4" and still got same errors – Tech-P Jul 24 '17 at 18:45
  • *What errors?* Is that even the correct route, and correct route parameter? None of the routing is shown in your question. Are you sure the value is coming through in your handler? Have you checked what value you're passing in? Have you tried your query in the mongo shell? – Adrian Jul 24 '17 at 18:48
  • Sorry, just re-read and saw your routing, and no, it doesn't appear to be the same parameter. In your route you have `_id`, but then you call `Param("id")`. When you run into an issue, it's important to check what values are getting passed around and if they're correct. – Adrian Jul 24 '17 at 18:49
  • new error " Unsupported document type for unmarshalling: []main.Poll 7:51:00 PM web.1 | [GIN] 2017/07/24 - 19:51:00 | 200 | 382.758µs | 127.0.0.1 | GET /polls/58d9cf1cdf353f3d2f5951b4 " – Tech-P Jul 24 '17 at 18:51
  • I'm guessing that's because it's a single result you're trying to unmarshal into a slice. But, it's progress: you've gotten past the issue you originally posted about! You can accept this answer if it solved your problem, but any further issues you'll have to troubleshoot and then post a new question if necessary. – Adrian Jul 24 '17 at 18:53
  • nope, thats not the question, "Errors Getting polls by id from mongoDB with go-gin and mgo " – Tech-P Jul 24 '17 at 18:55
  • But you just said you didn't get a not found error, you got a "Unsupported document type for unmarshalling" error. – Adrian Jul 24 '17 at 18:59
0

Change polls from an array:

 polls := []Poll{}

TO:

polls := Poll{}
Tech-P
  • 1
  • 2