-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongo.go
More file actions
56 lines (50 loc) · 1.17 KB
/
mongo.go
File metadata and controls
56 lines (50 loc) · 1.17 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
package gomongo
import (
"context"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"time"
)
func StrToObjId(id *string) *bson.ObjectID {
if id == nil {
return nil
}
objID, err := bson.ObjectIDFromHex(*id)
if err != nil {
panic(err)
}
return &objID
}
func ConnectToMongo(uri string) *mongo.Client {
opts := options.Client().ApplyURI(uri).SetBSONOptions(&options.BSONOptions{ObjectIDAsHexString: true})
client, err := mongo.Connect(opts)
if err != nil {
panic(err)
}
ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)
err = client.Ping(ctx, readpref.Primary())
return client
}
func ObjIdToStr(id *bson.ObjectID) *string {
if id == nil {
return nil
}
hex := (*id).Hex()
return &hex
}
func ObjIdListToStrList(list []bson.ObjectID) []string {
var result []string
for _, item := range list {
result = append(result, item.Hex())
}
return result
}
func StrListToObjIdList(list []string) []bson.ObjectID {
var result []bson.ObjectID
for _, item := range list {
result = append(result, *StrToObjId(&item))
}
return result
}