forked from cherry-game/cherry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo_test.go
53 lines (41 loc) · 1010 Bytes
/
mongo_test.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 cherryMongo
import (
"context"
"fmt"
"testing"
clog "github.com/cherry-game/cherry/logger"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type Student struct {
Name string
Age int
}
func TestConnect(t *testing.T) {
clog.Info("test connect mongodb")
uri := "mongodb://localhost:27017"
dbName := "test"
mdb, err := CreateDatabase(uri, dbName)
if err != nil {
clog.Warn(err)
return
}
collection := mdb.Collection("numbers")
student := &Student{
Name: "aaa222",
Age: 111,
}
res, err := collection.InsertOne(context.Background(), student)
insertID := res.InsertedID
clog.Infof("id = %v, err = %v", insertID, err)
//id, _ := primitive.ObjectIDFromHex("649160b6c637f5773cc1e818")
id, ok := insertID.(primitive.ObjectID)
if !ok {
return
}
findFilter := bson.M{"_id": id}
findResult := collection.FindOne(context.Background(), findFilter)
findStudent := Student{}
findResult.Decode(&findStudent)
fmt.Println(findStudent)
}