Defining a MongoDB Schema/Collection in mgo

huangapple go评论83阅读模式
英文:

Defining a MongoDB Schema/Collection in mgo

问题

我想使用mgo来创建/保存一个MongoDB集合。但我希望能更详细地定义它(例如,指定一个属性是必需的,另一个属性是枚举类型并具有默认值)。

我已经像这样定义了结构体,但不知道如何描述它的约束条件。

type Company struct {
    Name        string `json:"name" bson:"name"` // --> 我希望这个属性是必需的
    CompanyType string `json:"companyType" bson:"companyType"` // --> 我希望这个属性是枚举类型
}

在mgo中是否可以实现这样的功能,就像在MongooseJS中一样?

英文:

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

得分: 1

mgo不是一个ORM或验证工具。mgo只是与MongoDB的接口。

自己进行验证并不是坏事。

type CompanyType int

const (
  CompanyA CompanyType = iota // 这是默认值
  CompanyB CompanyType
  CompanyC CompanyType
)

type Company struct {
  Name        string
  CompanyType string
}

func (c Company) Valid() bool {
  if c.Name == "" {
    return false
  }
  // 如果是用户输入,您可能希望验证CompanyType的底层整数是否超出枚举范围。
  if c.CompanyType < CompanyA || c.CompanyType > CompanyB {
    return false
  }
  return true
}

点击这里了解更多关于Go中枚举的信息。

英文:

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 == &quot;&quot; {
    return false
  }
  // If it&#39;s a user input, you&#39;d want to validate CompanyType&#39;s underlying
  // integer isn&#39;t out of the enum&#39;s range.
  if c.CompanyType &lt; CompanyA || c.CompanyType &gt; CompanyB {
    return false
  }
  return true
}

Check this out for more about enums in Go.

huangapple
  • 本文由 发表于 2016年2月17日 19:57:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/35456076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定