/
mongo.go
109 lines (97 loc) · 2.43 KB
/
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"context"
"github.com/chidiwilliams/flatbson"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
dbName = "field_test"
colName = "users"
)
type Client struct {
cli *mongo.Client
}
func newClient(ctx context.Context) (*Client, error) {
client, err := mongo.Connect(
ctx,
options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
return nil, err
}
if err := client.Ping(ctx, nil); err != nil {
return nil, err
}
return &Client{client}, nil
}
func (m *Client) GetUser(ctx context.Context, id string) (User, error) {
col := m.cli.Database(dbName).Collection(colName)
u := User{}
err := col.FindOne(ctx, bson.M{"_id": id}).Decode(&u)
if err != nil {
return User{}, err
}
return u, nil
}
func (m *Client) GetUserWithInline(ctx context.Context, id string) (UserWithInline, error) {
col := m.cli.Database(dbName).Collection(colName)
u := UserWithInline{}
err := col.FindOne(ctx, bson.M{"_id": id}).Decode(&u)
if err != nil {
return UserWithInline{}, err
}
return u, nil
}
func (m *Client) UpdateUser(ctx context.Context, u User) error {
col := m.cli.Database(dbName).Collection(colName)
opt := options.Update().SetUpsert(true)
_, err := col.UpdateOne(ctx, bson.M{"_id": u.ID}, bson.M{
"$set": u,
}, opt)
if err != nil {
return err
}
return nil
}
func (m *Client) UpdateUserRaw(ctx context.Context, u User) error {
col := m.cli.Database(dbName).Collection(colName)
opt := options.Update().SetUpsert(true)
_, err := col.UpdateOne(ctx, bson.M{"_id": u.ID}, bson.M{
"$set": bson.M{
"age": u.Age,
"address.city": u.Address.City,
"address.zipcode": u.Address.Zipcode,
},
}, opt)
if err != nil {
return err
}
return nil
}
func (m *Client) UpdateUserWithInline(ctx context.Context, u UserWithInline) error {
col := m.cli.Database(dbName).Collection(colName)
opt := options.Update().SetUpsert(true)
_, err := col.UpdateOne(ctx, bson.M{"_id": u.ID}, bson.M{
"$set": u,
}, opt)
if err != nil {
return err
}
return nil
}
func (m *Client) UpdateUserWithFlatbson(ctx context.Context, u User) error {
col := m.cli.Database(dbName).Collection(colName)
opt := options.Update().SetUpsert(true)
doc, err := flatbson.Flatten(u)
if err != nil {
return err
}
_, err = col.UpdateOne(ctx, bson.M{"_id": u.ID}, bson.M{
"$set": doc,
}, opt)
if err != nil {
return err
}
return nil
}