我如何使用 go-gin 和 MongoDB 按 id 查询民意调查,我尝试了几种方法但我仍然遇到错误(未找到),似乎无法在下面找到我的代码,我的数据库打开数据库:

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

请您参考如下方法:

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

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!