Problem creating records with Gorm

Hey there!

I’m trying to setup a function to save a POST request to my cohort table. These are being saved successfully, but my ID increments by 2 when a record with existing name is trying to be saved.

For instance, I post

{
  "name": "Cohort 1",
  "description": "This should be the cohort 1"
}

I get the data back, because it was created successfully:

{
  "id": 1,
  "name": "Cohort 1",
  "description": "This should be the cohort 1",
  # timestamps 
}

However, if I try to post it again, it won’t save, which is intended because the name must be unique, but the next time a record is saved the ID is the previous record + 2.

I.e. I tried to save the previous record again, I would get a response with ID 0

{
  "id": 0,
  "name": "Cohort 1",
  "description": "This should be the cohort 1",
  # timestamps 
}

It is not saved to the database, however, next time I save a record, the ID isn’t the previous + 1.

If I were to post a new cohort right now, I would expect it to have id 2, however it’s saved with id 3.

{
  "name": "Cohort 2",
  "description": "This should be the cohort 2"
}

Response:

{
  "id": 3,
  "name": "Cohort 2",
  "description": "This should be the cohort 2",
  # timestamps 
}

I don’t understand why this happens.

This is my structure:

package models

import "time"

// Cohort represents a cohort of the site
type Cohort struct {
	ID          uint   `gorm:"primary_key" json:"id"`
	Name        string `gorm:"not_null;unique" json:"name"`
	Description string `gorm:"not_null" json:"description"`

	Users []User `json:"users,omitempty"`

	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
}

And my HandlerFunc:

func CreateCohort(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	db := utils.InitDB()
	defer db.Close()

	var cohort models.Cohort

	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&cohort)
	if err != nil {
		utils.JSONMessage(w, "Wrong body", http.StatusBadRequest)
	}

	if cohort.Name != "" && cohort.Description != "" {
		db.Create(&cohort)
	} else {
		utils.JSONMessage(w, "Name and Description are required", http.StatusBadRequest)
	}

	respBody, err := json.MarshalIndent(cohort, "", " ")
	if err != nil {
		log.Fatalf("Error returning created cohort: %v", err)
	}

	utils.JSONResponse(w, respBody, http.StatusCreated)
}

Any help would be awesome, thanks for your time!

You need to put a return after each utils.JSONMessage call as that will not terminate handing the request.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.