-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument.go
More file actions
65 lines (54 loc) · 1.47 KB
/
document.go
File metadata and controls
65 lines (54 loc) · 1.47 KB
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
package mango
import (
"context"
"reflect"
"time"
"github.com/entropyx/mango/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
opts "go.mongodb.org/mongo-driver/mongo/options"
)
type D bson.D
type M bson.M
type Document struct {
ID primitive.ObjectID `bson:"_id"`
CreatedAt *time.Time
UpdatedAt *time.Time
Context context.Context
}
func (m *Document) SetContext(c context.Context) {
m.Context = c
}
func (m *Document) GetContext() context.Context {
return m.Context
}
func (d *Document) Connection() *Connection {
v := d.Context.Value(keyConnection)
return v.(*Connection)
}
func (d *Document) Find(filter interface{}, value interface{}, ops ...*options.Find) error {
var findOptions []*opts.FindOptions
collection := d.collection(value)
for _, op := range ops {
skip := (op.Page - 1) * op.Limit
findOptions = append(findOptions, &opts.FindOptions{Limit: &op.Limit, Skip: &skip})
}
result, err := collection.Find(d.Context, filter, findOptions...)
if err != nil {
return err
}
return result.All(d.Context, value)
}
func (d *Document) collection(model interface{}) *mongo.Collection {
return d.Connection().collection(model)
}
func getDocument(iface interface{}) *Document {
v := reflect.ValueOf(iface)
if k := v.Kind(); k != reflect.Ptr {
panic("should be a pointer")
}
el := v.Elem()
docField := el.FieldByName("Document")
return docField.Addr().Interface().(*Document)
}