forked from ungerik/go-start
-
Notifications
You must be signed in to change notification settings - Fork 0
/
documentbase.go
76 lines (61 loc) · 1.71 KB
/
documentbase.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package mongo
import (
"github.com/ungerik/go-start/errs"
"github.com/ungerik/go-start/model"
"github.com/ungerik/go-start/mgo/bson"
)
///////////////////////////////////////////////////////////////////////////////
// DocumentBase
type DocumentBase struct {
ID bson.ObjectId `bson:"_id,omitempty" gostart:"-"`
collection *Collection `gostart:"-"`
embeddingStruct interface{} `gostart:"-"`
}
func (self *DocumentBase) Init(collection *Collection, embeddingStruct interface{}) {
if collection == nil {
panic("mongo.DocumentBase.Init() called with collection == nil")
}
if embeddingStruct == nil {
panic("mongo.DocumentBase.Init() called with embeddingStruct == nil")
}
self.collection = collection
self.embeddingStruct = embeddingStruct
InitRefs(embeddingStruct)
}
func (self *DocumentBase) Collection() *Collection {
if self == nil {
return nil
}
return self.collection
}
func (self *DocumentBase) ObjectId() bson.ObjectId {
if self == nil {
return ""
}
return self.ID
}
func (self *DocumentBase) SetObjectId(id bson.ObjectId) {
self.ID = id
}
func (self *DocumentBase) Iterator() model.Iterator {
return model.NewObjectIterator(self.embeddingStruct)
}
func (self *DocumentBase) Ref() Ref {
return Ref{self.ID, self.collection.Name}
}
func (self *DocumentBase) Save() error {
if self.embeddingStruct == nil {
return errs.Format("Can't save uninitialized mongo.Document. embeddingStruct is nil.")
}
if !self.ID.Valid() {
id, err := self.Collection().Insert(self.embeddingStruct)
if err == nil {
self.ID = id
}
return err
}
return self.collection.Update(self.ID, self.embeddingStruct)
}
func (self *DocumentBase) Remove() error {
return self.collection.Remove(self.ID)
}