/
mongo.go
58 lines (49 loc) · 2.21 KB
/
mongo.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
package mongo_helper
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type connector struct {
collection *mongo.Collection
}
type Connector interface {
InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)
FindOne(ctx context.Context, filter interface{}, structToDeserialize interface{}, opts ...*options.FindOneOptions) error
Delete(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)
FindAll(ctx context.Context, predicate bson.M, structToDeserialize interface{}, opts ...*options.FindOptions) error
UpdateOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)
}
func (c *connector) Delete(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return c.collection.DeleteOne(ctx, filter)
}
func (c *connector) UpdateOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return c.collection.UpdateOne(ctx, filter, update, opts...)
}
func (c *connector) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error) {
return c.collection.InsertOne(ctx, document, opts...)
}
func (c *connector) FindOne(ctx context.Context, filter interface{}, structToDeserialize interface{}, opts ...*options.FindOneOptions) error {
raw, err := c.collection.FindOne(ctx, filter, opts...).DecodeBytes()
if err != nil {
return err
}
return bson.UnmarshalWithContext(bsoncodec.DecodeContext{
Registry: bson.DefaultRegistry,
Truncate: true,
}, raw, structToDeserialize)
}
func (c *connector) FindAll(ctx context.Context, filter bson.M, structToDeserialize interface{}, opts ...*options.FindOptions) error {
cursor, err := c.collection.Find(ctx, filter, opts...)
if err != nil {
return err
}
return cursor.All(ctx, structToDeserialize)
}
func New(collection *mongo.Collection) Connector {
return &connector{
collection: collection,
}
}