-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_control.go
46 lines (38 loc) · 1.22 KB
/
db_control.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
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
DBCollectionInstitute = "institute"
DBCollectionTeacher = "teacher"
DBCollectionCourse = "course"
DBCollectionCourseRecord = "course_record"
DBCollectionCourseComment = "course_comment"
DBCollectionRelative = "relative"
DBCollectionStudent = "student"
DBCollectionCloudMedia = "cloudmedia"
DBCollectionStudentRelativeRef = "student_relative_ref"
DBCollectionStudentCourseRef = "student_course_ref"
)
var dbPool *mongo.Database
func dbPoolInit(sc *ServerConfig) (*mongo.Database, error) {
dbURL := fmt.Sprintf("mongodb://%s:%s@%s/%s", sc.DBUsername, sc.DBPassword, sc.DBHostAddress, sc.DBName)
dbClientOptions := options.Client().ApplyURI(dbURL)
dbClientOptions.SetConnectTimeout(5 * time.Second)
// Connect to MongoDB
dbClient, connErr := mongo.Connect(context.TODO(), dbClientOptions)
if connErr != nil {
return nil, connErr
}
// Check the connection
pingErr := dbClient.Ping(context.TODO(), nil)
if pingErr != nil {
return nil, pingErr
}
database := dbClient.Database(sc.DBName)
return database, nil
}