-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbfunctions.go
77 lines (68 loc) · 1.7 KB
/
dbfunctions.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
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
const dbname = "authdb"
const usercollname = "users"
func initDB(ctx context.Context) error {
uri := "mongodb://localhost:27017"
if uri == "" {
log.Fatal("Set your 'MONGODB_URI' environment variable. " +
"See: " +
"www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable")
}
client, err := mongo.Connect(ctx, options.Client().
ApplyURI(uri))
if err != nil {
return err
}
gdbclient = client
coll := getCollection(dbname, usercollname)
indexModel := mongo.IndexModel{
Keys: bson.D{{Key: "email", Value: 1}},
Options: options.Index().SetUnique(true),
}
_, err = coll.Indexes().CreateOne(ctx, indexModel)
if err != nil {
panic(err)
}
/*defer func() {
if err := client.Disconnect(ctx); err != nil {
panic(err)
}
}()*/
return nil
}
func getCollection(dbName, collName string) *mongo.Collection {
database := gdbclient.Database(dbname)
coll := database.Collection(collName)
return coll
}
func findOne(key string, result interface{}) error {
coll := getCollection(dbname, usercollname)
err := coll.FindOne(context.TODO(), bson.D{{"email", key}}).
Decode(&result)
if err == mongo.ErrNoDocuments {
fmt.Printf("No document was found with the email %s\n", key)
return err
}
if err != nil {
panic(err)
}
return nil
}
func insert(ctx context.Context, u User) error {
coll := getCollection(dbname, usercollname)
log.Printf("inserting %+v", u)
_, err := coll.InsertOne(ctx, u)
if err != nil {
fmt.Println("Something went wrong trying to insert the new documents:")
return err
}
return nil
}