我在使用Go 的官方 MongoDB 驱动程序为某些数据创建唯一索引时遇到一些问题。
所以我有一个这样的结构:
type Product struct {
ID primitive.ObjectID `json:"_id" bson:"_id"`
Name string `json:"name" bson:"name"`
Price float64 `json:"price" bson:"price"`
Attribute []Attribute `json:"attribute" bson:"attribute"`
Category string `json:"category" bson:"category"`
}
Run Code Online (Sandbox Code Playgroud)
然后我想为该name属性创建一个唯一索引。我尝试在我的函数中做类似的事情Create(对于产品)
func Create(c echo.Context) error {
//unique index here
indexModel, err := productCollection.Indexes().CreateOne(context.Background(),
IndexModel{
Keys: bsonx.Doc{{"name", bsonx.Int32(1)}},
Options: options.Index().SetUnique(true),
})
if err != nil {
log.Fatalf("something went wrong: %+v", err)
}
//create the product here
p := new(Product)
if err := c.Bind(p); err != nil …Run Code Online (Sandbox Code Playgroud) 我对 Go 比较陌生,为了快速掌握,我尝试用 Go 重写我的一些 JavaScript(NodeJS) 代码。最近我遇到了一个绊脚石,我发现 Go 没有三元运算符。例如在 JavaScript 中,我可以这样做:
const pageNumber: number = query.pageNumber ? parseInt(query.pageNumber, 10): 1;
Run Code Online (Sandbox Code Playgroud)
此处的查询代表 Req.query
但是我发现我不能用 Go 做同样的事情,我不得不写一个 if-else 语句。我只想知道为什么 Go 世界中不存在这种情况的原因是什么(是否有一些设计原则来说明为什么会这样)