package mgocrud import ( "reflect" "strings" "time" "gopkg.in/mgo.v2/bson" ) // ModelInterface is interface for mgo crud operations type ModelInterface interface { PrepareInsert() PrepareUpdate() GetID() *bson.ObjectId SetID(id *bson.ObjectId) GetIdentSelector() (selector bson.M) SetIdent() } // Model is model with default fields type Model struct { ID *bson.ObjectId `json:"id,omitempty" bson:"_id" mapstructure:"id"` InsertTime *time.Time `json:"insertTime,omitempty" bson:"insertTime,omitempty" index:"single" mapstructure:"Datum"` UpdateTime *time.Time `json:"updateTime,omitempty" bson:"updateTime,omitempty" index:"single" mapstructure:"Datum"` Ident []string `json:"ident,omitempty" bson:"-" mapstructure:"-"` } // GetCollectionName gets name from type func GetCollectionName(m ModelInterface) string { if i, ok := m.(interface { GetCollectionName() string }); ok { return i.GetCollectionName() } return strings.ToLower( reflect.TypeOf( reflect.Indirect(reflect.ValueOf(m)).Interface(), ).Name()) } // PrepareInsert creates new bson id and insert time func (m *Model) PrepareInsert() { if m.ID == nil { id := bson.NewObjectId() m.ID = &id } now := time.Now() m.InsertTime = &now m.UpdateTime = &now } // PrepareUpdate updates UpdateTime func (m *Model) PrepareUpdate() { now := time.Now() m.UpdateTime = &now } // GetID gets object id func (m *Model) GetID() *bson.ObjectId { return m.ID } // SetID sets object id func (m *Model) SetID(id *bson.ObjectId) { m.ID = id }