feat(controller): create index in database
This commit is contained in:
parent
0b85b4aca0
commit
8d10205878
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
"go.mongodb.org/mongo-driver/mongo/options"
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||||||
)
|
)
|
||||||
|
|
@ -11,6 +12,7 @@ import (
|
||||||
//TODO: create another package fo structs and interfaces
|
//TODO: create another package fo structs and interfaces
|
||||||
|
|
||||||
type Database struct {
|
type Database struct {
|
||||||
|
client *mongo.Client
|
||||||
devices *mongo.Collection
|
devices *mongo.Collection
|
||||||
users *mongo.Collection
|
users *mongo.Collection
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
|
|
@ -18,11 +20,14 @@ type Database struct {
|
||||||
|
|
||||||
func NewDatabase(ctx context.Context, mongoUri string) Database {
|
func NewDatabase(ctx context.Context, mongoUri string) Database {
|
||||||
var db Database
|
var db Database
|
||||||
|
|
||||||
clientOptions := options.Client().ApplyURI(mongoUri)
|
clientOptions := options.Client().ApplyURI(mongoUri)
|
||||||
client, err := mongo.Connect(ctx, clientOptions)
|
client, err := mongo.Connect(ctx, clientOptions)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
db.client = client
|
||||||
|
|
||||||
log.Println("Trying to ping Mongo database...")
|
log.Println("Trying to ping Mongo database...")
|
||||||
err = client.Ping(ctx, nil)
|
err = client.Ping(ctx, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -30,10 +35,24 @@ func NewDatabase(ctx context.Context, mongoUri string) Database {
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("Connected to MongoDB-->", mongoUri)
|
log.Println("Connected to MongoDB-->", mongoUri)
|
||||||
|
|
||||||
devices := client.Database("oktopus").Collection("devices")
|
devices := client.Database("oktopus").Collection("devices")
|
||||||
|
createIndexes(ctx, devices)
|
||||||
|
|
||||||
users := client.Database("oktopus").Collection("users")
|
users := client.Database("oktopus").Collection("users")
|
||||||
db.devices = devices
|
db.devices = devices
|
||||||
db.users = users
|
db.users = users
|
||||||
db.ctx = ctx
|
db.ctx = ctx
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func createIndexes(ctx context.Context, devices *mongo.Collection) {
|
||||||
|
indexField := bson.M{"sn": 1}
|
||||||
|
_, err := devices.Indexes().CreateOne(ctx, mongo.IndexModel{
|
||||||
|
Keys: indexField,
|
||||||
|
Options: options.Index().SetUnique(true),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("ERROR to create index in database:", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user