我正在学习围棋和杜松子wine 框架. 我构建了一个连接到MongoDB集合的简单微服务,一切正常,但当我使用POST添加文档时,它会添加"id"字段,而不是生成键"_id"字段,有什么方法可以避免这种情况吗?
这是我的乐趣:
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}})
}
这是我的模型:
type Post struct {
ID primitive.ObjectID
Title string `validate:"required,gte=2,lte=20"`
Article string `validate:"required,gte=4,lte=40"`
}