dongshou6041 2016-02-17 11:57
浏览 38
已采纳

在mgo中定义MongoDB模式/集合

I want to use mgo to create/save a MongoDB collection. But I would like to define it more extensively (for e.g to mention that one of the attribute is mandatory, another one is of an enum type and has a default value).

I have defined the struct like this, but don't know how to describe the constraints on it.

type Company struct {
    Name        string `json:"name" bson:"name"` // --> I WANT THIS TO BE MANDATORY
    CompanyType string `json:"companyType" bson:"companyType"` // -->I WANT THIS TO BE AN ENUM
}

Is this possible to do in mgo, like how we can do it in MongooseJS?

  • 写回答

1条回答 默认 最新

  • doupao3662 2016-02-17 14:43
    关注

    mgo isn't an ORM or a validation tool. mgo is only an interface to MongoDB.

    It's not bad to do validation all by yourself.

    type CompanyType int
    
    const (
      CompanyA CompanyType = iota // this is the default
      CompanyB CompanyType
      CompanyC CompanyType
    )
    
    type Company struct {
      Name string
      CompanyType string
    }
    
    func (c Company) Valid() bool {
      if c.Name == "" {
        return false
      }
      // If it's a user input, you'd want to validate CompanyType's underlying
      // integer isn't out of the enum's range.
      if c.CompanyType < CompanyA || c.CompanyType > CompanyB {
        return false
      }
      return true
    }
    

    Check this out for more about enums in Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据