mirror-nourybot/pkg/db/connect.go

95 lines
1.7 KiB
Go
Raw Normal View History

2021-10-25 23:33:00 +02:00
package db
import (
"context"
"fmt"
"time"
"github.com/lyx0/nourybot/pkg/config"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func Connect() {
conf := config.LoadConfig()
client, err := mongo.NewClient(options.Client().ApplyURI(conf.MongoURI))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
/*
List databases
*/
databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
log.Fatal(err)
}
fmt.Println(databases)
2021-10-25 23:46:27 +02:00
// Interact with data
type Channel struct {
Name string `bson:"name,omitempty"`
}
/*
Get my collection instance
*/
collection := client.Database("nourybot").Collection("channels")
/*
Insert channel
*/
2021-10-26 01:28:19 +02:00
// chnl := []interface{}{
// bson.D{{"name", "nouryqt"}},
// bson.D{{"name", "nourybot"}},
// }
2021-10-25 23:46:27 +02:00
2021-10-26 01:28:19 +02:00
// res, insertErr := collection.InsertMany(ctx, chnl)
// if insertErr != nil {
// log.Fatal(insertErr)
// }
// log.Info(res)
2021-10-25 23:46:27 +02:00
/*
Iterate a cursor
*/
2021-10-26 01:28:19 +02:00
// var result bson.M
// err = collection.FindOne(ctx, bson.D{{}}).Decode(&result)
// if err != nil {
// if err == mongo.ErrNoDocuments {
// return
// }
// panic(err)
// }
// log.Info(result["name"])
//------------------------------
cur, currErr := collection.Find(ctx, bson.D{{}})
2021-10-25 23:46:27 +02:00
if currErr != nil {
panic(currErr)
}
defer cur.Close(ctx)
2021-10-26 01:28:19 +02:00
var results []bson.M
if err = cur.All(ctx, &results); err != nil {
2021-10-25 23:46:27 +02:00
panic(err)
}
2021-10-26 01:28:19 +02:00
for _, result := range results {
fmt.Println(result["name"])
}
//------------------------------
2021-10-25 23:33:00 +02:00
}