为每个获取请求获取“_id:000000000”

我最近开始使用GO并尝试创建一个API。这是一个基本的 API,只有很少的端点。每个端点都工作正常,只有一个。我正在执行与其他获取终端节点相同的操作,但不明白为什么我从mongoDB获取空实例。据我所知,我认为这是由于数据类型引起的问题。


这是我的结构。getpostPost


package models


import (

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

}

这是控制器getPost


package controller


import (

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

}

这是我的main


package main


import (

    "insta/controller"


    "github.com/gin-gonic/gin"

)


func main() {

    router := gin.Default()

    router.GET("/posts/:postId" , controller.GetPost)

    router.Run()

}

我得到了这个回应。

http://img3.mukewang.com/633c1dd30001bffb11140083.jpg

PostId有效


http://img.mukewang.com/633c1ddd0001c0e605010103.jpg

ibeautiful
浏览 67回答 1
1回答

一只甜甜圈

问题是来自参数的 postId 是类型,而 mongodb 中的 postId 是类型不同的。stringprimitive.ObjectID解决方案是在查询之前将其转换为MongoDB。ObjectIDfunc 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})}
打开App,查看更多内容
随时随地看视频慕课网APP