dongseshu0698 2017-07-24 17:47
浏览 41
已采纳

错误使用go-gin和mgo从mongoDB按ID获取民意调查

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

2条回答 默认 最新

  • dr897777 2017-07-29 21:50
    关注

    Change polls from an array:

     polls := []Poll{}
    

    TO:

    polls := Poll{}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序:渲染收货地址时页面不显示
  • ¥20 win7 64位DirectShow提示初始化失败如何解决?
  • ¥20 小规模孤立词识别系统设计
  • ¥15 关于Java对接海康威视车牌识别一体机SDK是否需要固定外网的IP?
  • ¥15 Linux扩容时,格式化卡住了:vgdispaly查看卷组信息,没有输出
  • ¥18 关于#ubuntu#的问题:使用背景-工作职责内有七八台ubuntu系统的电脑,平时需要互相调取资料,想实现把这几台电脑用交换机组成一个局域网,来实现指定文件夹的互相调取和写入
  • ¥20 求一个简易射频信号综测仪
  • ¥15 esp8266 tally灯 接收端改为发射端
  • ¥30 Labview代码调用access 数据库,相同代码其中一个调用不出来是为什么
  • ¥15 基于51单片机的交通灯系统,找改程序有点急