【问题标题】:How to map enums to Bson&Json to store in mongoDB in Golang如何将枚举映射到 Bson&Json 以存储在 Golang 的 mongoDB 中
【发布时间】:2022-08-22 19:47:23
【问题描述】:

我遇到了一种情况,我的 MongoDB 有一个存储为字符串的字段,我需要确保该字段只有特定的枚举值。 同样,我应该只收到具有相同枚举的请求,并且应该能够将该结构变量作为枚举无处不在。

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

    标签: json mongodb go bson


    【解决方案1】:

    您的枚举是字符串类型。

    你可以这样声明

    package emums
    
    type StudentType string
    

    你的枚举

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

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多