-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
56 lines (44 loc) · 1.17 KB
/
main.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
package main
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"entrlcom.dev/mongox/collection"
)
type Person struct {
DataOfBirth time.Time `bson:"data_of_birth,omitempty"`
Name string `bson:"name,omitempty"`
TimeCreated time.Time `bson:"time_created,omitempty"`
}
type Repository struct {
client *mongo.Client
collection *mongo.Collection
}
func (x Repository) Create(ctx context.Context, person Person) error {
return collection.Insert[Person](x.collection).Insert(ctx, person)
}
func NewRepository(client *mongo.Client) Repository {
return Repository{
client: client,
collection: client.Database("example").Collection("person"),
}
}
func main() {
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
if err != nil {
// TODO: Handle error.
return
}
repository := NewRepository(client)
if err := repository.Create(ctx, Person{
DataOfBirth: time.Date(2020, time.May, 15, 0, 0, 0, 0, time.UTC),
Name: "John Doe",
TimeCreated: time.Now().UTC(),
}); err != nil {
// TODO: Handle error.
return
}
// ...
}