我正在使用以下 go 文件作为我的 http API 和 mgo 之间的层:
package store
import (
"reflect"
"strings"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type Manager struct {
collection *mgo.Collection
}
type Model interface {
Id() bson.ObjectId
}
func (m *Manager) index(model Model) {
v := reflect.ValueOf(model).Elem()
var index, unique []string
for i := 0; i < v.NumField(); i++ {
t := v.Type().Field(i)
if s := t.Tag.Get("store"); len(s) != 0 {
if strings.Contains(s, "index") {
index = append(index, t.Name)
}
if strings.Contains(s, "unique") {
unique = append(unique, t.Name)
}
}
}
m.collection.EnsureIndex(mgo.Index{Key: index})
m.collection.EnsureIndex(mgo.Index{Key: unique, Unique: true})
}
func (m *Manager) Create(model Model) error {
m.index(model)
return m.collection.Insert(model)
}
func (m *Manager) Update(model Model) error {
m.index(model)
return m.collection.UpdateId(model.Id(), model)
}
func (m *Manager) Destroy(model Model) error {
m.index(model)
return m.collection.RemoveId(model.Id())
}
func (m *Manager) Find(query Query, models interface{}) error {
return m.collection.Find(query).All(models)
}
func (m *Manager) FindOne(query Query, model Model) error {
m.index(model)
return m.collection.Find(query).One(model)
}
如您所见,我通过调用来确保每个操作的索引m.index(model)
。模型类型具有 formstore:"index"
或的标签store:"unique"
。
由于设置通用索引与设置唯一索引不同,我分别收集它们,然后调用m.collection.EnsureIndex
已解析的键。
然而,第二次调用m.collection.EnsureIndex
永远不会到达服务器,只发送了正常索引。
查看godocs显示确保 Index 缓存其调用,所以我认为我应该将它们组合在一个调用中。
那么如何在一次调用 EnsureIndex 时组合不同的索引设置?
解决方案: 您需要将reflect中的字段名称小写才能与mgo一起使用...