-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbson_string.go
76 lines (67 loc) · 1.54 KB
/
bson_string.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 goutils
import (
"fmt"
"strings"
"gopkg.in/mgo.v2/bson"
)
func ToObjectId(idHex string) (id bson.ObjectId, err error) {
if !bson.IsObjectIdHex(idHex) {
err = fmt.Errorf("Invalid input to ObjectIdHex: %q", idHex)
return
}
id = bson.ObjectIdHex(idHex)
return
}
// The Lite version of ToObjectId with no error return
func ToObjectIdOrBlank(idHex string) bson.ObjectId {
if !bson.IsObjectIdHex(idHex) {
return ""
}
return bson.ObjectIdHex(idHex)
}
func ToObjectIdOrBlankInterface(id bson.ObjectId) interface{} {
if id.Valid() {
return id
}
return ""
}
// ["1", "2", "3"] -> [ObjectId("1"), ObjectId("2"), ObjectId("3")]
func TurnPlainIdsToObjectIds(idHexes []string) (r []bson.ObjectId, err error) {
for _, id := range idHexes {
if strings.Trim(id, " ") == "" {
continue
}
oId, err := ToObjectId(id)
if err != nil {
return r, err
}
r = append(r, oId)
}
return
}
// [ObjectId("1"), ObjectId("2"), ObjectId("3")]-> ["1", "2", "3"]
func TurnObjectIdToPlainIds(ids []bson.ObjectId) (r []string) {
for _, id := range ids {
r = append(r, id.Hex())
}
return
}
func IsInObjectIds(tragetId bson.ObjectId, ids []bson.ObjectId) bool {
for _, id := range ids {
if tragetId == id {
return true
}
}
return false
}
// "1,2,3" -> [ObjectId("1"), ObjectId("2"), ObjectId("3")]
func TurnCommaStringsToObjectIds(commaStr string) (r []bson.ObjectId) {
ids := strings.Split(commaStr, ",")
for _, id := range ids {
if strings.Trim(id, " ") == "" {
continue
}
r = append(r, bson.ObjectIdHex(id))
}
return
}