-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.go
53 lines (46 loc) · 1021 Bytes
/
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
package mongodb
import (
"context"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type DB struct {
c *mongo.Client
db *mongo.Database
ctx context.Context
}
func New(uri string, dbName string) (*DB, error) {
ctx := context.TODO()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
return nil, err
}
db := client.Database(dbName)
return &DB{
c: client,
db: db,
ctx: ctx,
}, nil
}
func (m *DB) GetCollection(n string) *mongo.Collection {
return m.db.Collection(n)
}
func TransformId(id string) (primitive.ObjectID, error) {
i, err := primitive.ObjectIDFromHex(id)
if err != nil {
return primitive.NilObjectID, err
}
return i, nil
}
func TransformIds(ids []string) ([]primitive.ObjectID, error) {
oids := []primitive.ObjectID{}
for _, id := range ids {
i, err := TransformId(id)
if err != nil {
return nil, err
}
oids = append(oids, i)
}
return oids, nil
}