使用Go和Gin向MongoDB插入文档时生成id而非_id的解决方法
问题描述
我正在学习Go和Gin框架,搭建了一个连接MongoDB集合的简单微服务。目前所有功能正常,但通过POST请求添加文档时,生成的是"id"字段而非MongoDB默认的"_id"字段,请问有办法解决这个问题吗?
CreatePost函数代码
func (r *Rest) CreatePost(c *gin.Context) { var postCollection = database.GetCollection(r.db, "GoDB") ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) post := new(model.Post) defer cancel() if err := c.ShouldBindJSON(&post); err != nil { c.JSON(http.StatusBadRequest, gin.H{"message": err}) log.Fatal(err) return } // validation if err := post.Validate(); err == nil { c.JSON(http.StatusOK, gin.H{"input": "valid"}) } else { c.JSON(http.StatusBadRequest, gin.H{"input validation": err.Error()}) return } postPayload := model.Post{ ID: primitive.NewObjectID(), Title: post.Title, Article: post.Article, } result, err := postCollection.InsertOne(ctx, postPayload) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"message": err}) return } c.JSON(http.StatusOK, gin.H{"message": "Posted succesfully", "Data": map[string]interface{}{"data": result}}) }
Post模型代码
type Post struct { ID primitive.ObjectID Title string `validate:"required,gte=2,lte=20"` Article string `validate:"required,gte=4,lte=40"` }
MongoDB返回文档示例

解决方案
问题根源在于Post结构体未指定MongoDB字段映射标签,驱动默认将Go驼峰字段名转为小写(如ID变成id)。只需给ID字段添加bson:"_id"标签,即可让驱动映射到MongoDB默认的_id字段。
修改后的Post模型代码:
type Post struct { ID primitive.ObjectID `bson:"_id"` Title string `validate:"required,gte=2,lte=20" bson:"title"` Article string `validate:"required,gte=4,lte=40" bson:"article"` }
额外建议:给其他字段也加上bson标签,明确控制数据库中的字段命名(比如转为小写的title、article),避免自动转换带来的意外问题。
如果需要返回前端的JSON中仍显示id而非_id,可同时添加json:"id"标签,实现存储与返回的字段名分离:
type Post struct { ID primitive.ObjectID `bson:"_id" json:"id"` Title string `validate:"required,gte=2,lte=20" bson:"title" json:"title"` Article string `validate:"required,gte=4,lte=40" bson:"article" json:"article"` }
内容的提问来源于stack exchange,提问作者user20174493
相关产品推荐
相关产品推荐

