在 mgo 中定义一个 MongoDB Schema/Collection
Defining a MongoDB Schema/Collection in mgo
我想使用 mgo 来 create/save 一个 MongoDB 集合。但我想更广泛地定义它(例如提到其中一个属性是强制性的,另一个是枚举类型并具有默认值)。
我已经定义了这样的结构,但不知道如何描述它的约束。
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
}
这可以在 mgo 中实现吗,就像我们如何在 MongooseJS 中实现一样?
mgo 不是 ORM 或验证工具。 mgo 只是 MongoDB.
的接口
自己验证也不错
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
}
查看 this 以了解有关 Go 中枚举的更多信息。
我想使用 mgo 来 create/save 一个 MongoDB 集合。但我想更广泛地定义它(例如提到其中一个属性是强制性的,另一个是枚举类型并具有默认值)。
我已经定义了这样的结构,但不知道如何描述它的约束。
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
}
这可以在 mgo 中实现吗,就像我们如何在 MongooseJS 中实现一样?
mgo 不是 ORM 或验证工具。 mgo 只是 MongoDB.
的接口自己验证也不错
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
}
查看 this 以了解有关 Go 中枚举的更多信息。