How to map enums to Bson&Json to store in mongoDB in Golang

Viewed 43

I came up with a situation where my MongoDB has a field stored as a string and I need to ensure that field has only specific enum values. Similarly, I should be getting requests with the same enums only and should be able to that struct variable everywhere as an enum.

type studentModel struct {
      studentType enums.StudentType `bson:"studentType, omitempty" json:"studentType,omitempty"`
      studentId int64 `bson:"studentId, omitempty" json:"studentId,omitempty"`
    }


    studentType Enum Values : PAID , UNPAID , INACTIVE
1 Answers

Your enum is of type string.

Your can declare it like this

package enums

type StudentType string

Your enums

const (
    PAID enums.StudentType = "PAID"
    UNPAID enums.StudentType = "UNPAID"
    INACTIVE enums.StudentType = "INACTIVE"
)
type studentModel struct {
    studentType enums.StudentType `bson:"studentType,omitempty" json:"studentType,omitempty"`
    studentId   int64             `bson:"studentId,omitempty" json:"studentId,omitempty"`
}
Related