为了账号安全,请及时绑定邮箱和手机立即绑定

为每个获取请求获取“_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 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信