-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
44 lines (42 loc) · 1.04 KB
/
base.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
package mongo
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"reflect"
"strings"
)
func FindIdField(modelType reflect.Type) (int, string, string) {
return FindField(modelType, "_id")
}
func FindField(modelType reflect.Type, bsonName string) (int, string, string) {
numField := modelType.NumField()
for i := 0; i < numField; i++ {
field := modelType.Field(i)
bsonTag := field.Tag.Get("bson")
tags := strings.Split(bsonTag, ",")
json := field.Name
if tag1, ok1 := field.Tag.Lookup("json"); ok1 {
json = strings.Split(tag1, ",")[0]
}
for _, tag := range tags {
if strings.TrimSpace(tag) == bsonName {
return i, field.Name, json
}
}
}
return -1, "", ""
}
func Exist(ctx context.Context, collection *mongo.Collection, id interface{}) (bool, error) {
query := bson.M{"_id": id}
x := collection.FindOne(ctx, query)
if x.Err() != nil {
if fmt.Sprint(x.Err()) == "mongo: no documents in result" {
return false, nil
} else {
return false, x.Err()
}
}
return true, nil
}