I'm learning Go and Gin framework. I built a simple microservice connected to a MongoDB collection, everything works but when I add a document using a POST it adds the "id" field instead of generating the key "_id" field, is there a way to avoid this?
This is my func:
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}})
}
This is my model:
type Post struct {
ID primitive.ObjectID
Title string `validate:"required,gte=2,lte=20"`
Article string `validate:"required,gte=4,lte=40"`
}