亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為每個獲取請求獲取“_id:000000000”

為每個獲取請求獲取“_id:000000000”

Go
ibeautiful 2022-10-04 19:49:13
我最近開始使用GO并嘗試創建一個API。這是一個基本的 API,只有很少的端點。每個端點都工作正常,只有一個。我正在執行與其他獲取終端節點相同的操作,但不明白為什么我從mongoDB獲取空實例。據我所知,我認為這是由于數據類型引起的問題。這是我的結構。getpostPostpackage modelsimport (    "time"    "go.mongodb.org/mongo-driver/bson/primitive")type Posts struct {    Id       primitive.ObjectID `json:"id" bson:"_id" validate:"nil=false"`    Caption  string             `json:"caption" bson:"caption"`    ImageUrl string             `json:"imageUrl" bson:"imageUrl" validate:"nil=false"`    Author   string             `json:"author" bson:"author" validate:"nil:false"`    Time     time.Time          `json:"time" bson:"time"`}這是控制器getPostpackage controllerimport (    "insta/models"    "log"    "net/http"    "github.com/gin-gonic/gin"    "go.mongodb.org/mongo-driver/bson"    // "go.mongodb.org/mongo-driver/bson/primitive")func GetPost(c *gin.Context) {    var post models.Posts    postId := c.Param("postId")    client, ctx, cancel := getConnection()    defer cancel()    defer client.Disconnect(ctx)    err := client.Database("instagram").Collection("posts").FindOne(ctx, bson.M{"_id": postId}).Decode(&post)    if err != nil {        log.Printf("Couldn't get the Post")    }    c.JSON(http.StatusOK, gin.H{"post": post})}這是我的mainpackage mainimport (    "insta/controller"    "github.com/gin-gonic/gin")func main() {    router := gin.Default()    router.GET("/posts/:postId" , controller.GetPost)    router.Run()}我得到了這個回應。PostId有效
查看完整描述

1 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

問題是來自參數的 postId 是類型,而 mongodb 中的 postId 是類型不同的。stringprimitive.ObjectID


解決方案是在查詢之前將其轉換為MongoDB。ObjectID


func GetPost(c *gin.Context) {

    var post models.Posts

    postId := c.Param("postId")

    postObjectId, err := primitive.ObjectIDFromHex(postId)

    if err != nil {

        c.JSON(http.StatusBadRequest, gin.H{"message": "PostID is not a valid ObjectID"})

        return

    }


    client, ctx, cancel := getConnection()

    defer cancel()

    defer client.Disconnect(ctx)


    err = client.Database("instagram").Collection("posts").FindOne(ctx, bson.M{"_id": postObjectId}).Decode(&post)

    // Check if document exists return 404 error

    if errors.Is(err, mongo.ErrNoDocuments) {

        c.JSON(http.StatusNotFound, gin.H{"message": "Post with the given id does not exist"})

        return

    }


    // Mongodb network or server error

    if err != nil {

        c.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})

        return

    }


    c.JSON(http.StatusOK, gin.H{"post": post})

}


查看完整回答
反對 回復 2022-10-04
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號