【问题标题】:Errors Getting polls by id from mongoDB with go-gin and mgo使用 go-gin 和 mgo 从 mongoDB 获取民意调查时出错
【发布时间】:2017-12-30 09:53:59
【问题描述】:

我如何使用 go-gin 和 MongoDB 按 id 查询民意调查,我尝试了几种方法,但仍然出现错误(未找到),似乎找不到下面是我的代码,我的数据库在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)

}

我的数据库如下:

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

【问题讨论】:

  • 我对答案进行了猜测,但“我仍然会遇到错误”并没有太大的意义。请用您遇到的具体错误更新您的问题。
  • 错误是:“未找到”

标签: mongodb web-services go mongodb-query go-gin


【解决方案1】:

您的 ID 是 ObjectId,但您的输入是 string。您需要使用bson.ObjectIdHexstring 解析为ObjectId

err := db.C(CollectionPoll).FindId(bson.ObjectIdHex(id)).One(&poll)

【讨论】:

  • "1" 不是有效的 BSON ObjectId,根据我链接到的文档,如果它无效,ObjectIdHex 会恐慌。
  • 好的...你改变了什么?您是否为集合中存在的文档传递了有效的 ObjectId?当您使用 mongo 客户端手动执行查询时,它是否有效?
  • 我这样做了“localhost:5000/polls/58d9cf1cdf353f3d2f5951b4”,但仍然遇到同样的错误
  • 什么错误? 那是不是正确的路由和正确的路由参数?您的问题中没有显示任何路由。你确定你的处理程序中的价值是通过的吗?你检查过你传入的值吗?您是否在 mongo shell 中尝试过查询?
  • 对不起,只是重新阅读并查看了您的路由,不,它似乎不是同一个参数。在您的路线中,您有_id,但随后您拨打Param("id")。当您遇到问题时,检查传递的值以及它们是否正确非常重要。
【解决方案2】:

从数组中更改投票:

 polls := []Poll{}

到:

polls := Poll{}

【讨论】:

    猜你喜欢
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    相关资源
    最近更新 更多